From f4eece21dd5bde3f88ed6ac403c880167c4757ba Mon Sep 17 00:00:00 2001 From: AlexisDrogoul Date: Sat, 29 Jan 2022 22:47:23 +0700 Subject: [PATCH] Cleansing commit - Removes 250++ warnings (emitted by Java and the annotation processor) - Removes an annoying false positive error emitted by the annotation processor regarding ISkill / IAgent subclasses. - Adds a simple COUNTER class based on AtomicInteger to the "developer tools" and bases all computation of unique indices (SymbolDescription.index, etc.) on it --- .../genstar/utils/GenStarGamaSurveyUtils.java | 249 +- .../extensions/database/species/AgentDB.java | 137 +- .../operator/PedestrianNetwork.java | 289 +- .../skills/PedestrianRoadSkill.java | 215 +- .../extensions/skills/PedestrianSkill.java | 636 +++- msi.gama.application/.classpath | 2 +- .../.settings/org.eclipse.jdt.core.prefs | 8 + .../workbench/GamaActionBarAdvisor.java | 274 +- .../workbench/PerspectiveHelper.java | 10 +- .../application/workbench/ThemeHelper.java | 8 +- .../workspace/WorkspaceModelsManager.java | 11 +- .../gama/common/geometry/GeometryUtils.java | 614 ++- .../preferences/GamaPreferenceStore.java | 10 +- .../src/msi/gama/common/preferences/Pref.java | 8 +- .../src/msi/gama/common/util/FileUtils.java | 261 +- .../src/msi/gama/common/util/GISUtils.java | 20 +- .../src/msi/gama/common/util/JavaUtils.java | 92 +- .../src/msi/gama/common/util/PoolUtils.java | 101 +- .../exploration/ExplicitExploration.java | 44 +- .../gama/kernel/batch/optimization/Swarm.java | 373 +- .../gama/kernel/experiment/BatchAgent.java | 128 +- .../kernel/experiment/ParameterAdapter.java | 84 +- .../msi/gama/metamodel/shape/GamaShape.java | 154 +- .../gama/metamodel/topology/graph/AStar.java | 133 +- .../topology/graph/GraphTopology.java | 438 ++- .../topology/graph/NBAStarPathfinder.java | 150 +- .../topology/grid/FieldDiffuser.java | 164 +- .../metamodel/topology/grid/GridDiffuser.java | 252 +- .../topology/grid/GridMooreNeighborhood.java | 35 +- .../msi/gama/outputs/ImageDisplaySurface.java | 11 +- .../outputs/layers/GraphicLayerStatement.java | 8 +- .../gama/outputs/layers/LightStatement.java | 9 +- .../charts/ChartJFreeChartOutputPie.java | 80 +- .../src/msi/gama/runtime/ExecutionScope.java | 14 +- .../msi/gama/runtime/HeadlessListener.java | 10 +- .../src/msi/gama/runtime/MemoryUtils.java | 26 +- .../src/msi/gama/runtime/PlatformHelper.java | 9 +- .../msi/gama/runtime/benchmark/Benchmark.java | 62 +- .../exceptions/GamaRuntimeException.java | 228 +- .../src/msi/gama/util/GamaListFactory.java | 298 +- .../src/msi/gama/util/file/GamaCSVFile.java | 172 +- .../src/msi/gama/util/file/GamaDXFFile.java | 355 +- .../msi/gama/util/file/GamaGraphDimacs.java | 46 +- .../msi/gama/util/file/GamaGraphDotFile.java | 58 +- .../src/msi/gama/util/file/GamaGraphFile.java | 67 +- .../src/msi/gama/util/file/GamaGraphGML.java | 55 +- .../src/msi/gama/util/file/GamaGraphGexf.java | 55 +- .../msi/gama/util/file/GamaGraphGraph6.java | 55 +- .../msi/gama/util/file/GamaGraphMLFile.java | 45 +- .../msi/gama/util/file/GamaGraphTsplib.java | 43 +- .../src/msi/gama/util/file/GamaGridFile.java | 72 +- .../src/msi/gama/util/file/GamaShapeFile.java | 70 +- .../src/msi/gama/util/file/GamlFileInfo.java | 12 +- .../src/msi/gama/util/file/csv/CsvReader.java | 4 +- .../src/msi/gama/util/graph/GamaGraph.java | 36 +- .../src/msi/gama/util/matrix/GamaField.java | 160 +- .../gama/util/matrix/GamaObjectMatrix.java | 156 +- .../src/msi/gaml/compilation/GAML.java | 7 +- .../src/msi/gaml/compilation/Symbol.java | 89 +- .../gaml/descriptions/ActionDescription.java | 131 +- .../gaml/descriptions/ModelDescription.java | 249 +- .../gaml/descriptions/SkillDescription.java | 84 +- .../descriptions/StatementDescription.java | 164 +- .../gaml/descriptions/SymbolDescription.java | 12 +- .../gaml/descriptions/ValidationContext.java | 146 +- .../src/msi/gaml/operators/Cast.java | 330 +- .../src/msi/gaml/operators/Dates.java | 547 ++- .../src/msi/gaml/operators/Files.java | 462 ++- .../src/msi/gaml/operators/Random.java | 222 +- .../src/msi/gaml/operators/Spatial.java | 10 +- .../src/msi/gaml/operators/System.java | 13 +- .../src/msi/gaml/skills/MovingSkill.java | 454 ++- .../src/msi/gaml/skills/MovingSkill3D.java | 53 +- .../msi/gaml/statements/AspectStatement.java | 10 +- .../msi/gaml/statements/CaptureStatement.java | 19 +- .../msi/gaml/statements/CreateStatement.java | 48 +- .../msi/gaml/statements/SaveStatement.java | 436 ++- .../draw/ShapeDrawingAttributes.java | 59 +- .../gaml/statements/test/AbstractSummary.java | 166 +- .../src/msi/gaml/types/GamaColorType.java | 3 +- .../src/msi/gaml/types/GamaFileType.java | 6 +- .../src/msi/gaml/types/GamaFontType.java | 50 +- .../src/msi/gaml/types/GamaGeometryType.java | 338 +- .../src/msi/gaml/types/GamaIntegerType.java | 55 +- .../src/msi/gaml/types/GamaNoType.java | 11 +- .../src/msi/gaml/types/GamaPointType.java | 40 +- .../src/msi/gaml/types/GamaSkillType.java | 15 +- .../src/msi/gaml/types/GamaSpeciesType.java | 41 +- .../src/msi/gaml/types/GamaStringType.java | 32 +- .../src/msi/gaml/types/GamaTopologyType.java | 61 +- .../msi/gaml/types/ParametricFileType.java | 2 +- msi.gama.core/src/msi/gaml/types/Types.java | 2 +- .../src/msi/gaml/variables/Variable.java | 9 +- .../src/msi/gama/doc/util/HomeToTOC.java | 438 ++- .../src/msi/gama/ext/kabeja/dxf/DXFBlock.java | 371 +- .../ext/kabeja/dxf/DXFDimensionStyle.java | 582 ++- .../msi/gama/ext/kabeja/dxf/DXFDocument.java | 962 +++-- .../msi/gama/ext/kabeja/dxf/DXFEllipse.java | 534 +-- .../src/msi/gama/ext/kabeja/dxf/DXFHatch.java | 696 ++-- .../gama/ext/kabeja/dxf/DXFHatchPattern.java | 136 +- .../msi/gama/ext/kabeja/dxf/DXFHeader.java | 138 +- .../src/msi/gama/ext/kabeja/dxf/DXFImage.java | 467 +-- .../src/msi/gama/ext/kabeja/dxf/DXFLayer.java | 542 +-- .../msi/gama/ext/kabeja/dxf/DXFLeader.java | 597 ++- .../src/msi/gama/ext/kabeja/dxf/DXFMLine.java | 340 +- .../msi/gama/ext/kabeja/dxf/DXFPolyline.java | 1400 +++---- .../msi/gama/ext/kabeja/dxf/DXFRegion.java | 106 +- .../msi/gama/ext/kabeja/dxf/DXFSpline.java | 487 +-- .../msi/gama/ext/kabeja/dxf/DXFVariable.java | 129 +- .../msi/gama/ext/kabeja/dxf/DXFViewport.java | 1192 +++--- .../kabeja/dxf/helpers/DXFMLineSegment.java | 149 +- .../dxf/helpers/DXFSplineConverter.java | 130 +- .../ext/kabeja/dxf/helpers/DXFTextParser.java | 1249 +++--- .../gama/ext/kabeja/dxf/helpers/DXFUtils.java | 309 +- .../kabeja/dxf/helpers/HatchBoundaryLoop.java | 145 +- .../kabeja/dxf/helpers/HatchLineIterator.java | 535 +-- .../kabeja/dxf/helpers/HatchLineSegment.java | 304 +- .../gama/ext/kabeja/dxf/helpers/Point.java | 185 +- .../kabeja/dxf/helpers/PolylineSegment.java | 626 +-- .../ext/kabeja/dxf/helpers/TextDocument.java | 199 +- .../ext/kabeja/dxf/objects/DXFDictionary.java | 440 ++- .../ext/kabeja/dxf/objects/DXFMLineStyle.java | 371 +- .../parser/DXFEntitiesSectionHandler.java | 269 +- .../parser/DXFObjectsSectionHandler.java | 207 +- .../msi/gama/ext/kabeja/parser/DXFParser.java | 577 +-- .../kabeja/parser/DXFTableSectionHandler.java | 247 +- .../ext/kabeja/parser/SAXParserBuilder.java | 408 +- .../dxf/filter/DXFStreamLayerFilter.java | 237 +- .../parser/dxf/filter/FilterExample.java | 74 +- .../parser/entities/DXFHatchHandler.java | 758 ++-- .../ext/kabeja/processing/LayerFilter.java | 186 +- .../kabeja/processing/PolylineConverter.java | 361 +- .../kabeja/processing/PostProcessManager.java | 106 +- .../processing/PostProcessorConfig.java | 111 +- .../kabeja/processing/ProcessPipeline.java | 205 +- .../kabeja/processing/ProcessingManager.java | 471 ++- .../processing/helper/PolylineQueue.java | 527 +-- .../gama/ext/kabeja/tools/CodePageParser.java | 155 +- .../gama/ext/kabeja/tools/ConfigHelper.java | 92 +- .../gama/ext/kabeja/tools/FontManager.java | 218 +- .../ext/kabeja/tools/SAXFilterConfig.java | 111 +- .../tools/SAXProcessingManagerBuilder.java | 287 +- .../ext/kabeja/tools/SAXSerializerConfig.java | 84 +- .../ext/kabeja/xml/AggregatorGenerator.java | 149 +- .../ext/kabeja/xml/SAXPrettyOutputter.java | 666 ++-- .../src/msi/gama/ext/kml/Feature.java | 3354 ++++++++--------- msi.gama.ext/src/msi/gama/ext/kml/Kml.java | 211 +- .../msi/gama/ext/kml/NetworkLinkControl.java | 1668 ++++---- msi.gama.ext/src/msi/gama/ext/kml/Pair.java | 892 ++--- .../src/msi/gama/ext/kml/Placemark.java | 1276 +++---- .../src/msi/gama/ext/kml/gx/FlyTo.java | 583 ++- .../src/msi/gama/ext/osmosis/Fileformat.java | 451 ++- .../headless/batch/ModelLibraryRunner.java | 57 +- .../headless/command/HeadlessStatement.java | 71 +- .../headless/command/StartSimulation.java | 31 + .../gama/headless/runtime/Application.java | 134 +- .../src/msi/gama/lang/gaml/EGaml.java | 20 +- .../plugins/msi.gama.processor_1.4.0.jar | Bin 295558 -> 295519 bytes .../gama/precompiler/ElementProcessor.java | 13 +- .../gama/precompiler/FactoryProcessor.java | 51 - .../gama/precompiler/OperatorProcessor.java | 4 + .../gama/precompiler/ProcessorContext.java | 42 +- .../architecture/simplebdi/LawStatement.java | 283 +- .../msi/gaml/architecture/simplebdi/Norm.java | 303 +- .../architecture/simplebdi/Operators.java | 1877 +++++++-- .../architecture/simplebdi/Predicate.java | 564 +-- .../architecture/simplebdi/PredicateType.java | 45 +- .../architecture/simplebdi/RuleStatement.java | 1567 ++++---- .../gaml/architecture/simplebdi/Sanction.java | 85 +- .../architecture/simplebdi/SocialLink.java | 329 +- .../build.properties | 4 +- .../collision/broadphase/Dbvt.java | 852 ++++- .../HashedOverlappingPairCache.java | 143 +- .../collision/shapes/QuantizedBvhNodes.java | 429 ++- .../linearmath/CProfileManager.java | 116 +- .../linearmath/convexhull/HullLibrary.java | 377 +- .../bulletphysics/util/ObjectArrayList.java | 153 +- .../box2d_version/Box2DPhysicalWorld.java | 30 +- .../java_version/BulletBodyWrapper.java | 45 +- .../NativeBulletBodyWrapper.java | 60 +- .../src/javax/vecmath/GVector.java | 217 +- .../traffic/driving/DrivingSkill.java | 2536 ++++++++----- .../traffic/driving/OldDrivingSkill.java | 260 +- .../extensions/traffic/driving/RoadSkill.java | 499 ++- .../carfollowing/CustomDualTreeBidiMap.java | 84 +- .../PublicTransportSchedulerSkill.java | 299 +- .../publictransport/PublicTransportSkill.java | 350 +- .../src/ummisco/gama/dev/utils/COUNTER.java | 32 + ummisco.gama.feature.dependencies/feature.xml | 7 - .../serial/MultiThreadedArduinoReceiver.java | 93 +- .../gama/network/skills/NetworkSkill.java | 27 +- .../gama/opengl/scene/ObjectDrawer.java | 3 +- .../gama/opengl/scene/layers/LayerObject.java | 14 +- .../gamaType/reference/ReferenceAgent.java | 31 +- .../ui/views/displays/LayerSideControls.java | 139 +- .../displays/LayeredDisplaySynchronizer.java | 23 +- .../ui/metadata/FileMetaDataProvider.java | 233 +- .../contents/WrappedSyntacticContent.java | 11 +- .../gama/ui/parameters/AbstractEditor.java | 9 +- .../gama/ui/parameters/GamaWizardPage.java | 48 +- .../src/ummisco/gama/ui/utils/SwtGui.java | 11 +- .../gama/ui/utils/WorkbenchHelper.java | 12 +- .../statements/DiffusionStatement.java | 50 +- 203 files changed, 32466 insertions(+), 20399 deletions(-) delete mode 100644 msi.gama.processor/src/msi/gama/precompiler/FactoryProcessor.java create mode 100644 ummisco.gama.annotations/src/ummisco/gama/dev/utils/COUNTER.java diff --git a/espacedev.gaml.extensions.genstar/src/espacedev/gaml/extensions/genstar/utils/GenStarGamaSurveyUtils.java b/espacedev.gaml.extensions.genstar/src/espacedev/gaml/extensions/genstar/utils/GenStarGamaSurveyUtils.java index 9373845008..6664d59562 100644 --- a/espacedev.gaml.extensions.genstar/src/espacedev/gaml/extensions/genstar/utils/GenStarGamaSurveyUtils.java +++ b/espacedev.gaml.extensions.genstar/src/espacedev/gaml/extensions/genstar/utils/GenStarGamaSurveyUtils.java @@ -1,3 +1,13 @@ +/******************************************************************************************************* + * + * GenStarGamaSurveyUtils.java, in espacedev.gaml.extensions.genstar, is part of the source code of the GAMA modeling + * and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package espacedev.gaml.extensions.genstar.utils; import java.io.FileNotFoundException; @@ -18,173 +28,217 @@ import msi.gama.util.file.csv.CsvReader.Stats; import msi.gaml.types.IType; import msi.gaml.types.Types; +import ummisco.gama.dev.utils.DEBUG; +/** + * The Class GenStarGamaSurveyUtils. + */ /* - * Encapsulation (more a copy/past) of CsvReader utilities to explore csv files + * Encapsulation (more a copy/past) of CsvReader utilities to explore csv files */ public class GenStarGamaSurveyUtils { - public GenStarGamaSurveyUtils(IScope scope, GamaCSVFile survey, List> atts) throws FileNotFoundException { - this.path = Paths.get(FileUtils.constructAbsoluteFilePath(scope, survey.getPath(scope), false)); - this.stats = CsvReader.getStats(this.path.toString(),null); + /** + * Instantiates a new gen star gama survey utils. + * + * @param scope + * the scope + * @param survey + * the survey + * @param atts + * the atts + * @throws FileNotFoundException + * the file not found exception + */ + public GenStarGamaSurveyUtils(final IScope scope, final GamaCSVFile survey, + final List> atts) throws FileNotFoundException { + this.path = Paths.get(FileUtils.constructAbsoluteFilePath(scope, survey.getPath(scope), false)); + this.stats = CsvReader.getStats(this.path.toString(), null); this.atts = atts; } - + + /** The stats. */ private final Stats stats; + + /** The path. */ private final Path path; + + /** The atts. */ private final List> atts; - + + /** The row header number. */ // All is here - private int[] rowHeaderNumber = new int[] {-1,-1}; - private int[] columnHeaderNumber = new int[] {-1,-1}; - @SuppressWarnings("rawtypes") - private IType inferedType = null; + private final int[] rowHeaderNumber = { -1, -1 }; + + /** The column header number. */ + private final int[] columnHeaderNumber = { -1, -1 }; + + /** The infered type. */ + @SuppressWarnings ("rawtypes") private IType inferedType = null; + + /** The total. */ private Double total = null; - + /** * TODO : find the number of row headers + * * @return */ public int inferRowHeaders() { - if (rowHeaderNumber[0]==-1) { - + if (rowHeaderNumber[0] == -1) { + CsvReader reader = null; int first = rowHeaderNumber[0]; int headerLength = 0; try { - reader = new CsvReader(path.toString(),stats.delimiter); + reader = new CsvReader(path.toString(), stats.delimiter); boolean isData = false; - - do { + + do { if (reader.readRecord()) { - List vals = Arrays.asList(reader.getValues()).stream() - .filter(s -> !s.isBlank()).collect(Collectors.toList()); - Optional> oa = atts.stream() - .filter(a -> a.getValueSpace().getValues().stream() - .allMatch(v -> vals.contains(v.getStringValue()))) - .findFirst(); - if (oa.isPresent()) { headerLength = oa.get().getValueSpace().getValues().size(); } else { isData = true; } + List vals = Arrays.asList(reader.getValues()).stream().filter(s -> !s.isBlank()) + .collect(Collectors.toList()); + Optional> oa = atts.stream().filter(a -> a.getValueSpace() + .getValues().stream().allMatch(v -> vals.contains(v.getStringValue()))).findFirst(); + if (oa.isPresent()) { + headerLength = oa.get().getValueSpace().getValues().size(); + } else { + isData = true; + } } first += 1; } while (!isData); - - + } catch (final IOException e) {} reader.close(); rowHeaderNumber[0] = first; columnHeaderNumber[1] = headerLength; } - + return rowHeaderNumber[0]; } - + /** * TODO : find the number of column headers + * * @return */ - public int inferColumnHeaders() { - if (columnHeaderNumber[0]==-1) { + public int inferColumnHeaders() { + if (columnHeaderNumber[0] == -1) { CsvReader reader = null; int first = 0; int columnLength = 0; try { - reader = new CsvReader(path.toString(),stats.delimiter); - + reader = new CsvReader(path.toString(), stats.delimiter); + int idx = inferRowHeaders(); - do { reader.skipLine(); } while (--idx>0); - + do { reader.skipLine(); } while (--idx > 0); + boolean isData = false; if (reader.readRecord()) { - List vals = Arrays.asList(reader.getValues()).stream() - .filter(s -> !s.isBlank()).collect(Collectors.toList()); + List vals = Arrays.asList(reader.getValues()).stream().filter(s -> !s.isBlank()) + .collect(Collectors.toList()); int tmp = 0; - do { + do { String current = vals.get(tmp++); - Optional> oa = atts.stream() - .filter(a -> a.getValueSpace().contains(current)) - .findFirst(); - if (oa.isPresent()) { - columnLength = oa.get().getValueSpace().getValues().size() > columnLength ? - oa.get().getValueSpace().getValues().size() : columnLength; + Optional> oa = + atts.stream().filter(a -> a.getValueSpace().contains(current)).findFirst(); + if (oa.isPresent()) { + columnLength = oa.get().getValueSpace().getValues().size() > columnLength + ? oa.get().getValueSpace().getValues().size() : columnLength; } else { isData = true; first = vals.indexOf(current); } - } - while (!isData); - + } while (!isData); + } - + } catch (final IOException e) {} reader.close(); columnHeaderNumber[0] = first; rowHeaderNumber[1] = columnLength; - + } return columnHeaderNumber[0]; } - + /** * Infer the type of data contains in the csv file + * * @return */ - @SuppressWarnings("rawtypes") + @SuppressWarnings ("rawtypes") public IType inferDataType() { - if (inferedType!=null) { return inferedType; } + if (inferedType != null) return inferedType; inferedType = Types.NO_TYPE; CsvReader reader = null; try { - - reader = new CsvReader(path.toString(),stats.delimiter); + + reader = new CsvReader(path.toString(), stats.delimiter); int idx = inferRowHeaders(); - do { reader.skipLine(); } while (--idx>0); - - if(reader.readRecord()) { + do { reader.skipLine(); } while (--idx > 0); + + if (reader.readRecord()) { String[] firstLineData = reader.getValues(); - inferedType = processRecordType(Arrays.copyOfRange(firstLineData,inferColumnHeaders(),firstLineData.length)); + inferedType = processRecordType( + Arrays.copyOfRange(firstLineData, inferColumnHeaders(), firstLineData.length)); } - + } catch (final IOException e) {} reader.close(); return inferedType; } - + /** - * Compute the sum of data contained in the csv file: if there is non numerical data, then + * Compute the sum of data contained in the csv file: if there is non numerical data, then + * * @return */ public Double getTotalData() { - if (total!=null) {return total;} - if (!inferedType.isNumber()) {total=-1d;} + if (total != null) return total; + if (!inferedType.isNumber()) { total = -1d; } CsvReader reader = null; try { - reader = new CsvReader(path.toString(),stats.delimiter); - int[] min = new int[] {inferRowHeaders(),inferColumnHeaders()}; - int[] max = new int[] {columnHeaderNumber[0]+columnHeaderNumber[1],rowHeaderNumber[0]+rowHeaderNumber[1]}; - System.out.println("Data matrix is"+min+max); + reader = new CsvReader(path.toString(), stats.delimiter); + int[] min = { inferRowHeaders(), inferColumnHeaders() }; + int[] max = { columnHeaderNumber[0] + columnHeaderNumber[1], rowHeaderNumber[0] + rowHeaderNumber[1] }; + DEBUG.OUT("Data matrix is" + DEBUG.TO_STRING(min) + DEBUG.TO_STRING(max)); int idx = min[0]; - do { reader.skipLine(); } while (--idx>0); - + do { reader.skipLine(); } while (--idx > 0); + int ldx = max[1]; while (ldx-- > 0) { - if(reader.readRecord()) { - String[] lineData = Arrays.copyOfRange(reader.getValues(),min[1],max[0]); - for (int i = 0; i < lineData.length; i++) {total += Double.valueOf(lineData[i]);} + if (reader.readRecord()) { + String[] lineData = Arrays.copyOfRange(reader.getValues(), min[1], max[0]); + for (String element : lineData) { total += Double.valueOf(element); } } } - - System.out.println("Total value is "+total); - + + System.out.println("Total value is " + total); + } catch (final IOException e) {} reader.close(); return total; } - - private class StringAnalysis { + /** + * The Class StringAnalysis. + */ + private static class StringAnalysis { + + /** The is float. */ boolean isFloat = true; + + /** The is int. */ boolean isInt = true; + /** + * Instantiates a new string analysis. + * + * @param s + * the s + */ StringAnalysis(final String s) { for (final char c : s.toCharArray()) { @@ -196,46 +250,55 @@ private class StringAnalysis { isInt = false; isFloat = false; break; - } else if (c == ',' || c == ';' || c == '|' || c == ':' || c == '/' - || Character.isWhitespace(c)) { + } else if (c == ',' || c == ';' || c == '|' || c == ':' || c == '/' || Character.isWhitespace(c)) { isInt = false; isFloat = false; } } } - if (isInt && isFloat) { - isFloat = false; - } + if (isInt && isFloat) { isFloat = false; } } } - - @SuppressWarnings("rawtypes") + + /** + * Process record type. + * + * @param values + * the values + * @return the i type + */ + @SuppressWarnings ("rawtypes") protected IType processRecordType(final String[] values) { IType temp = null; for (final String s : values) { final StringAnalysis sa = new StringAnalysis(s); if (sa.isInt) { - if (temp == null) { - temp = Types.INT; - } + if (temp == null) { temp = Types.INT; } } else if (sa.isFloat) { - if (temp == null || temp == Types.INT) { - temp = Types.FLOAT; - } + if (temp == null || temp == Types.INT) { temp = Types.FLOAT; } } else { temp = Types.NO_TYPE; } } // in case nothing has been read (i.e. empty file) - if (temp == null) { - temp = Types.NO_TYPE; - } + if (temp == null) { temp = Types.NO_TYPE; } return temp; } - + + /** + * Gets the path. + * + * @return the path + */ public Path getPath() { return path; } + + /** + * Gets the delimiter. + * + * @return the delimiter + */ public Character getDelimiter() { return stats.delimiter; } - + } diff --git a/irit.gaml.extensions.database/src/irit/gaml/extensions/database/species/AgentDB.java b/irit.gaml.extensions.database/src/irit/gaml/extensions/database/species/AgentDB.java index 060e5f8322..de2f2ec1b5 100644 --- a/irit.gaml.extensions.database/src/irit/gaml/extensions/database/species/AgentDB.java +++ b/irit.gaml.extensions.database/src/irit/gaml/extensions/database/species/AgentDB.java @@ -1,15 +1,13 @@ -/********************************************************************************************* +/******************************************************************************************************* * + * AgentDB.java, in irit.gaml.extensions.database, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * 'AgentDB.java', in plugin 'irit.gaml.extensions.database', is part of the source code of the GAMA modeling and - * simulation platform. (v. 1.8.1) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * - * (c) 2007-2020 UMI 209 UMMISCO IRD/UPMC & Partners - * - * Visit https://github.com/gama-platform/gama for license information and developers contact. - * - * - **********************************************************************************************/ + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package irit.gaml.extensions.database.species; import java.sql.Connection; @@ -29,6 +27,9 @@ import msi.gaml.types.IType; import ummisco.gama.dev.utils.DEBUG; +/** + * The Class AgentDB. + */ /* * @Author TRUONG Minh Thai * @@ -56,15 +57,36 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class AgentDB extends GamlAgent { + /** The conn. */ private Connection conn = null; + + /** The sql conn. */ private SqlConnection sqlConn = null; + + /** The is connection. */ private boolean isConnection = false; + + /** The params. */ private java.util.Map params = null; + /** + * Instantiates a new agent DB. + * + * @param s the s + * @param index the index + * @throws GamaRuntimeException the gama runtime exception + */ public AgentDB(final IPopulation s, final int index) throws GamaRuntimeException { super(s, index); } + /** + * Checks if is connected. + * + * @param scope the scope + * @return true, if is connected + * @throws GamaRuntimeException the gama runtime exception + */ @action ( name = "isConnected", doc = @doc ( @@ -74,6 +96,13 @@ public boolean isConnected(final IScope scope) throws GamaRuntimeException { return isConnection; } + /** + * Close. + * + * @param scope the scope + * @return the object + * @throws GamaRuntimeException the gama runtime exception + */ @action ( name = "close", doc = @doc ( @@ -87,10 +116,8 @@ public Object close(final IScope scope) throws GamaRuntimeException { // e.printStackTrace(); throw GamaRuntimeException.error("AgentDB.close error:" + e.toString(), scope); } catch (final NullPointerException npe) { - if (conn == null) { - throw GamaRuntimeException - .error("AgentDB.close error: cannot close a database connection that does not exist.", scope); - } + if (conn == null) throw GamaRuntimeException + .error("AgentDB.close error: cannot close a database connection that does not exist.", scope); } return null; @@ -104,6 +131,13 @@ public Object close(final IScope scope) throws GamaRuntimeException { // } // Get current time of system + /** + * Time stamp. + * + * @param scope the scope + * @return the long + * @throws GamaRuntimeException the gama runtime exception + */ // added from MaeliaSkill @action ( name = "timeStamp", @@ -111,10 +145,16 @@ public Object close(final IScope scope) throws GamaRuntimeException { value = "Get the current time of the system.", returns = "Current time of the system in millisecondes")) public Long timeStamp(final IScope scope) throws GamaRuntimeException { - final Long timeStamp = System.currentTimeMillis(); - return timeStamp; + return System.currentTimeMillis(); } + /** + * Connect DB. + * + * @param scope the scope + * @return the object + * @throws GamaRuntimeException the gama runtime exception + */ /* * Make a connection to BDMS * @@ -135,7 +175,7 @@ public Object connectDB(final IScope scope) throws GamaRuntimeException { params = (java.util.Map) scope.getArg("params", IType.MAP); - final String dbtype = params.get("dbtype"); + // final String dbtype = params.get("dbtype"); // Note BG: before 13/06/2020, SQLite was not supported in AgentDB. // The reason is not clear, a guess is that when an agent update the database file, // the file is locked and thus another agent cannot try to update it. @@ -149,9 +189,8 @@ public Object connectDB(final IScope scope) throws GamaRuntimeException { // further info).", // scope); // } - if (isConnection) { + if (isConnection) throw GamaRuntimeException.error("AgentDB.connection error: a connection is already opened", scope); - } try { sqlConn = SqlUtils.createConnectionObject(scope); conn = sqlConn.connectDB(); @@ -163,6 +202,13 @@ public Object connectDB(final IScope scope) throws GamaRuntimeException { // ---------------------------------------------------------------------------------------------------------- } + /** + * Test connection. + * + * @param scope the scope + * @return true, if successful + * @throws GamaRuntimeException the gama runtime exception + */ /* * Test a connection to DBMS * @@ -187,6 +233,13 @@ public boolean testConnection(final IScope scope) throws GamaRuntimeException { // --------------------------------------------------------------------------------------- } + /** + * Select. + * + * @param scope the scope + * @return the i list + * @throws GamaRuntimeException the gama runtime exception + */ /* * Make a connection to BDMS and execute the select statement * @@ -219,9 +272,7 @@ public boolean testConnection(final IScope scope) throws GamaRuntimeException { returns = "Returns the obtained result from executing the select statement.")) public IList select(final IScope scope) throws GamaRuntimeException { - if (!isConnection) { - throw GamaRuntimeException.error("AgentDB.select: Connection was not established ", scope); - } + if (!isConnection) throw GamaRuntimeException.error("AgentDB.select: Connection was not established ", scope); final String selectComm = (String) scope.getArg("select", IType.STRING); final IList values = (IList) scope.getArg("values", IType.LIST); // Boolean transform = scope.hasArg("transform") ? (Boolean) @@ -245,6 +296,13 @@ public IList select(final IScope scope) throws GamaRuntimeException { } + /** + * Execute update. + * + * @param scope the scope + * @return the int + * @throws GamaRuntimeException the gama runtime exception + */ /* * - Make a connection to BDMS - Executes the SQL statement in this PreparedStatement object, which must be an SQL * INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement. @@ -276,9 +334,7 @@ public IList select(final IScope scope) throws GamaRuntimeException { returns = "Returns the number of updated rows. ")) public int executeUpdate(final IScope scope) throws GamaRuntimeException { - if (!isConnection) { - throw GamaRuntimeException.error("AgentDB.select: Connection was not established ", scope); - } + if (!isConnection) throw GamaRuntimeException.error("AgentDB.select: Connection was not established ", scope); final String updateComm = (String) scope.getArg("updateComm", IType.STRING); final IList values = (IList) scope.getArg("values", IType.LIST); @@ -295,14 +351,19 @@ public int executeUpdate(final IScope scope) throws GamaRuntimeException { e.printStackTrace(); throw GamaRuntimeException.error("AgentDB.executeUpdate: " + e.toString(), scope); } - if (DEBUG.IS_ON()) { - DEBUG.OUT(updateComm + " was run"); - } + if (DEBUG.IS_ON()) { DEBUG.OUT(updateComm + " was run"); } return row_count; // ---------------------------------------------------------------------------------------------------- } + /** + * Gets the paramater. + * + * @param scope the scope + * @return the paramater + * @throws GamaRuntimeException the gama runtime exception + */ @action ( name = "getParameter", args = {}, @@ -313,6 +374,13 @@ public Object getParamater(final IScope scope) throws GamaRuntimeException { return params; } + /** + * Sets the parameter. + * + * @param scope the scope + * @return the object + * @throws GamaRuntimeException the gama runtime exception + */ @action ( name = "setParameter", args = { @arg ( @@ -338,6 +406,13 @@ public Object setParameter(final IScope scope) throws GamaRuntimeException { return null; } + /** + * Insert. + * + * @param scope the scope + * @return the int + * @throws GamaRuntimeException the gama runtime exception + */ /* * Make a connection to BDMS and execute the insert statement * @@ -373,9 +448,7 @@ public Object setParameter(final IScope scope) throws GamaRuntimeException { returns = "Returns the number of updated rows. ")) public int insert(final IScope scope) throws GamaRuntimeException { - if (!isConnection) { - throw GamaRuntimeException.error("AgentDB.select: Connection was not established ", scope); - } + if (!isConnection) throw GamaRuntimeException.error("AgentDB.select: Connection was not established ", scope); final String table_name = (String) scope.getArg("into", IType.STRING); final IList cols = (IList) scope.getArg("columns", IType.LIST); final IList values = (IList) scope.getArg("values", IType.LIST); @@ -401,9 +474,7 @@ public int insert(final IScope scope) throws GamaRuntimeException { e.printStackTrace(); throw GamaRuntimeException.error("AgentDB.insert: " + e.toString(), scope); } - if (DEBUG.IS_ON()) { - DEBUG.OUT("Insert into " + " was run"); - } + if (DEBUG.IS_ON()) { DEBUG.OUT("Insert into " + " was run"); } return rec_no; } diff --git a/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/operator/PedestrianNetwork.java b/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/operator/PedestrianNetwork.java index 6de3042a1d..d715980c6b 100644 --- a/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/operator/PedestrianNetwork.java +++ b/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/operator/PedestrianNetwork.java @@ -1,3 +1,13 @@ +/******************************************************************************************************* + * + * PedestrianNetwork.java, in miat.gaml.extensions.pedestrian, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package miat.gaml.extensions.operator; import java.util.Collections; @@ -22,43 +32,65 @@ import msi.gaml.types.Types; import ummisco.gama.dev.utils.DEBUG; +/** + * The Class PedestrianNetwork. + */ public class PedestrianNetwork { - - - @SuppressWarnings("unchecked") - public static IList generateNetwork(IScope scope, IList> obst, - IContainer bounds, IContainer regular_network, Boolean openArea, - boolean randomDist, double valDistForOpenArea, double valDensityOpenArea, - boolean cleanNetwork, double toleranceClip, double toleranceTriang, double minDistPath, double simplicationDistance, double sizeSquare){ - DEBUG.ON(); - DEBUG.OUT("Start generating pedestrian network"); - + /** + * Generate network. + * + * @param scope the scope + * @param obst the obst + * @param bounds the bounds + * @param regular_network the regular network + * @param openArea the open area + * @param randomDist the random dist + * @param valDistForOpenArea the val dist for open area + * @param valDensityOpenArea the val density open area + * @param cleanNetwork the clean network + * @param toleranceClip the tolerance clip + * @param toleranceTriang the tolerance triang + * @param minDistPath the min dist path + * @param simplicationDistance the simplication distance + * @param sizeSquare the size square + * @return the i list + */ + @SuppressWarnings ("unchecked") + public static IList generateNetwork(final IScope scope, final IList> obst, + final IContainer bounds, final IContainer regular_network, + final Boolean openArea, final boolean randomDist, final double valDistForOpenArea, + final double valDensityOpenArea, final boolean cleanNetwork, final double toleranceClip, + final double toleranceTriang, final double minDistPath, final double simplicationDistance, + final double sizeSquare) { + DEBUG.ON(); + DEBUG.OUT("Start generating pedestrian network"); double t = System.currentTimeMillis(); - + boolean walking_area = true; IShape walking_shape = scope.getSimulation().getGeometry().copy(scope); - if(bounds == null || bounds.isEmpty(scope)) { + if (bounds == null || bounds.isEmpty(scope)) { walking_area = false; } else { walking_shape = Spatial.Operators.union(scope, (IContainer) bounds).copy(scope); } IShape area = walking_shape.copy(scope); double t1 = System.currentTimeMillis(); - DEBUG.OUT("Processing walking area: "+(t1-t)); - - IList decomp = sizeSquare > 0.0 ? Spatial.Transformations.toSquares(scope, area, sizeSquare, true) : null; + DEBUG.OUT("Processing walking area: " + (t1 - t)); + + IList decomp = + sizeSquare > 0.0 ? Spatial.Transformations.toSquares(scope, area, sizeSquare, true) : null; double t1a = System.currentTimeMillis(); - DEBUG.OUT("|==> Processing squarification : "+(t1a-t1)/1000); - + DEBUG.OUT("|==> Processing squarification : " + (t1a - t1) / 1000); + for (IContainer shp : obst) { - for (IShape obs : shp.iterable(scope)) { + for (IShape obs : shp.iterable(scope)) { if (decomp == null) { - area = Operators.minus(scope, area, obs); + area = Operators.minus(scope, area, obs); } else { - IList geoms = Spatial.Queries.overlapping(scope, decomp, obs); + IList geoms = Spatial.Queries.overlapping(scope, decomp, obs); for (IShape a : geoms) { IShape b = Operators.minus(scope, a, obs); if (b != null) { @@ -70,88 +102,83 @@ public static IList generateNetwork(IScope scope, IList Remove obstacle from area : "+(t1b-t1a)/1000); - - if (area == null ) { - GamaRuntimeException.error("Get a null area when computing the background geometry", scope); - } + DEBUG.OUT("|==> Remove obstacle from area : " + (t1b - t1a) / 1000); + + if (area == null) + throw GamaRuntimeException.error("Get a null area when computing the background geometry", scope); area = keepMainGeom(area); - + double t2 = System.currentTimeMillis(); - DEBUG.OUT("|==> Keep main component : "+(t2-t1b)/1000); - - if (openArea) { - area = managementOpenArea(scope, area, randomDist, valDistForOpenArea, valDensityOpenArea); - } - + DEBUG.OUT("|==> Keep main component : " + (t2 - t1b) / 1000); + + if (openArea) { area = managementOpenArea(scope, area, randomDist, valDistForOpenArea, valDensityOpenArea); } + double t3 = System.currentTimeMillis(); - DEBUG.OUT("Processing open area: "+(t3-t2)); + DEBUG.OUT("Processing open area: " + (t3 - t2)); double valTolClip = toleranceClip; - double valTolTri =toleranceTriang; - + double valTolTri = toleranceTriang; - IList lines = Transformations.skeletonize(scope, area, valTolClip, valTolTri,false); + IList lines = Transformations.skeletonize(scope, area, valTolClip, valTolTri, false); - double t4 = System.currentTimeMillis(); - DEBUG.OUT("Skeletonization : "+(t4-t3)); - + DEBUG.OUT("Skeletonization : " + (t4 - t3)); + double valFiltering = minDistPath; if (valFiltering > 0.0) { final IShape areaTmp = area.getExteriorRing(scope); lines.removeIf(l -> areaTmp.euclidianDistanceTo(l) < minDistPath); } - + double t5 = System.currentTimeMillis(); - DEBUG.OUT("Clean skeletonized network : "+(t5-t4)); + DEBUG.OUT("Clean skeletonized network : " + (t5 - t4)); // If there is a walking area AND a regular network, combine pedestrian and regular network - if(walking_area && regular_network != null && !regular_network.isEmpty(scope)) { - return collapseNetwork(scope, walking_shape, obst, -1.0, lines, - (IList) regular_network.listValue(scope, Types.GEOMETRY, false)); - } + if (walking_area && regular_network != null && !regular_network.isEmpty(scope)) + return collapseNetwork(scope, walking_shape, obst, -1.0, lines, + (IList) regular_network.listValue(scope, Types.GEOMETRY, false)); double t6 = System.currentTimeMillis(); - DEBUG.OUT("Processing bi network : "+(t6-t5)); - + DEBUG.OUT("Processing bi network : " + (t6 - t5)); + IShape unionL = Operators.union(scope, lines); lines = Transformations.clean(scope, (IList) unionL.getGeometries(), 0.0, true, cleanNetwork); - + double t7 = System.currentTimeMillis(); - DEBUG.OUT("Clean final network : "+(t7-t6)); - + DEBUG.OUT("Clean final network : " + (t7 - t6)); + IList segments = GamaListFactory.create(); - + for (IShape g : lines) { - if (simplicationDistance > 0) - g = Transformations.simplification(scope, g, simplicationDistance); + if (simplicationDistance > 0) { g = Transformations.simplification(scope, g, simplicationDistance); } if (g.getPoints().size() == 2) { segments.add(g); - } - else if (g.getPoints().size() > 2) { + } else if (g.getPoints().size() > 2) { for (int i = 0; i < g.getPoints().size() - 1; i++) { IList coords = GamaListFactory.create(); coords.add(g.getPoints().get(i)); - coords.add(g.getPoints().get(i+1)); + coords.add(g.getPoints().get(i + 1)); IShape line = Creation.line(scope, coords); segments.add(line); } } } double t8 = System.currentTimeMillis(); - - DEBUG.OUT("To segments : "+(t8-t7)); + + DEBUG.OUT("To segments : " + (t8 - t7)); return segments; } - - public static IShape keepMainGeom(IShape inGeom) { + /** + * Keep main geom. + * + * @param inGeom the in geom + * @return the i shape + */ + public static IShape keepMainGeom(final IShape inGeom) { IShape result = inGeom; if (inGeom.getGeometries().size() > 1) { double maxArea = 0; @@ -166,63 +193,82 @@ public static IShape keepMainGeom(IShape inGeom) { } return result; } - - + + /** + * Management open area. + * + * @param scope the scope + * @param area the area + * @param randomDist the random dist + * @param valDistForOpenArea the val dist for open area + * @param valDensityOpenArea the val density open area + * @return the i shape + */ /* * Add small obstacle inside open area to increase the number of node for pedestrian movement */ - public static IShape managementOpenArea(IScope scope, IShape area, boolean randomDist, double valDistForOpenArea, double valDensityOpenArea) { + public static IShape managementOpenArea(final IScope scope, IShape area, final boolean randomDist, + final double valDistForOpenArea, final double valDensityOpenArea) { IShape areaTmp = Spatial.Transformations.reduced_by(scope, area, valDistForOpenArea); if (areaTmp != null) { List pts = GamaListFactory.create(Types.GEOMETRY); for (IShape g : areaTmp.getGeometries()) { - if (g == null || g.getArea() == 0) continue; + if (g == null || g.getArea() == 0) { continue; } long nbPoints = Math.round(g.getArea() * valDensityOpenArea); - if (nbPoints == 0) continue; + if (nbPoints == 0) { continue; } if (randomDist) { - for (int i = 0; i < nbPoints;i++) { - pts.add(Spatial.Punctal.any_location_in(scope, g)); - } - } - else { + for (int i = 0; i < nbPoints; i++) { pts.add(Spatial.Punctal.any_location_in(scope, g)); } + } else { double dimension = Math.sqrt(g.getArea() / nbPoints); List squares = Spatial.Transformations.toSquares(scope, g, dimension); - for (IShape sq : squares) pts.add(sq.getCentroid()); + for (IShape sq : squares) { pts.add(sq.getCentroid()); } } } for (GamaPoint pt : pts) { - area = Operators.minus(scope, area, Spatial.Transformations.enlarged_by(scope, pt,0.01,5)); + area = Operators.minus(scope, area, Spatial.Transformations.enlarged_by(scope, pt, 0.01, 5)); } } return area; } - + // ------------------------------------------ // // COMBINE REGULAR CORRIDOR WITH 2D CORRIDORS // // ------------------------------------------ // + /** + * Collapse network. + * + * @param scope the scope + * @param pedestrianArea the pedestrian area + * @param obst the obst + * @param buffer the buffer + * @param pedestrianNetwork the pedestrian network + * @param regularNetwork the regular network + * @return the i list + */ /* - * Method that collapse a regular network (usually road network) where pedestrian will move using moving skill on network - * (see PEDESTRAIN_ROAD_STATUS) and pedestrian virtual network (computed using Delaunay's triangulation and skeletonization) where - * agent will move using SFM or other continuous movement model + * Method that collapse a regular network (usually road network) where pedestrian will move using moving skill on + * network (see PEDESTRAIN_ROAD_STATUS) and pedestrian virtual network (computed using Delaunay's triangulation and + * skeletonization) where agent will move using SFM or other continuous movement model */ - @SuppressWarnings("unchecked") - public static IList collapseNetwork(IScope scope, IShape pedestrianArea, IList> obst, - double buffer, IList pedestrianNetwork, IList regularNetwork){ - + @SuppressWarnings ("unchecked") + public static IList collapseNetwork(final IScope scope, final IShape pedestrianArea, + final IList> obst, final double buffer, + final IList pedestrianNetwork, final IList regularNetwork) { + // Output IList currentLines = GamaListFactory.create(); - + DEBUG.OUT("Clean regular and pedestrian network"); - + IList rNetwork = Transformations.clean(scope, - (IList) Operators.union(scope, regularNetwork).getGeometries(),0.0,true,false); + (IList) Operators.union(scope, regularNetwork).getGeometries(), 0.0, true, false); IList pNetwork = Transformations.clean(scope, - (IList) Operators.union(scope, pedestrianNetwork).getGeometries(),0.0,true,true); + (IList) Operators.union(scope, pedestrianNetwork).getGeometries(), 0.0, true, true); DEBUG.OUT("Remove edges within pedestrian area from regular network"); - + IList toConnect = GamaListFactory.create(); for (IShape e : rNetwork) { // Road sections not within pedestrian area @@ -231,66 +277,59 @@ public static IList collapseNetwork(IScope scope, IShape pedestrianArea, if (!pedestrianArea.intersects(e)) { e.setAttribute(PedestrianRoadSkill.PEDESTRIAN_ROAD_STATUS, PedestrianRoadSkill.SIMPLE_STATUS); currentLines.add(e); - // For road sections that cross walking area, cut it with open area and find connecting point + // For road sections that cross walking area, cut it with open area and find connecting point } else { IShape s = Operators.minus(scope, e, pedestrianArea); s.setAttribute(PedestrianRoadSkill.PEDESTRIAN_ROAD_STATUS, PedestrianRoadSkill.SIMPLE_STATUS); currentLines.add(s); - + IShape fs = s.getPoints().firstValue(scope); IShape ls = s.getPoints().lastValue(scope); - toConnect.add(fs.euclidianDistanceTo(pedestrianArea) < ls.euclidianDistanceTo(pedestrianArea) ? - fs : ls); + toConnect.add( + fs.euclidianDistanceTo(pedestrianArea) < ls.euclidianDistanceTo(pedestrianArea) ? fs : ls); } } } - + DEBUG.OUT("Add all pedestrian corridor from pedestrian network"); - - for(IShape corridors : pNetwork) { + + for (IShape corridors : pNetwork) { corridors.setAttribute(PedestrianRoadSkill.PEDESTRIAN_ROAD_STATUS, PedestrianRoadSkill.COMPLEX_STATUS); currentLines.add(corridors); } - + IList obstacles = GamaListFactory.create(); for (IContainer shp : obst) { - for (IShape obs : shp.iterable(scope)) { - obstacles.add(obs); - } + for (IShape obs : shp.iterable(scope)) { obstacles.add(obs); } } - + IShape o = Operators.union(scope, obstacles); - + DEBUG.OUT("Iterate over potential connecting points (corridor that cross the pedestrian area boundaries)"); - - IList pNodes = pNetwork.stream(scope) - .flatMap(corridor -> corridor.getPoints().stream()) - .collect(Collectors.toSet()).stream() - .collect(GamaListFactory.toGamaList()); - for (IShape pt : toConnect ) { - - Map candidateNodes = pNodes.stream(scope) - .collect(Collectors.toMap(node -> node, node -> pt.euclidianDistanceTo(node))); - - + + IList pNodes = pNetwork.stream(scope).flatMap(corridor -> corridor.getPoints().stream()) + .collect(Collectors.toSet()).stream().collect(GamaListFactory.toGamaList()); + for (IShape pt : toConnect) { + + Map candidateNodes = + pNodes.stream(scope).collect(Collectors.toMap(node -> node, node -> pt.euclidianDistanceTo(node))); + IList newLinks = GamaListFactory.create(); - - if(newLinks.isEmpty()) { - IShape cn = Collections.min(candidateNodes.entrySet(), - Comparator.comparing(Entry::getValue)).getKey(); + + if (newLinks.isEmpty()) { + IShape cn = Collections.min(candidateNodes.entrySet(), Comparator.comparing(Entry::getValue)).getKey(); newLinks.add(Creation.link(scope, cn, pt)); - } - - for(IShape connection : newLinks.stream().filter(link -> !link.crosses(o)).collect(Collectors.toList())) { + } + + for (IShape connection : newLinks.stream().filter(link -> !link.crosses(o)).collect(Collectors.toList())) { connection.setAttribute(PedestrianRoadSkill.PEDESTRIAN_ROAD_STATUS, PedestrianRoadSkill.COMPLEX_STATUS); currentLines.add(connection); } - + } - - + return currentLines; - + } - + } diff --git a/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianRoadSkill.java b/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianRoadSkill.java index 7fa524af7d..58cbb8fd24 100644 --- a/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianRoadSkill.java +++ b/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianRoadSkill.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * simtools.gaml.extensions.traffic.RoadSkill.java, in plugin simtools.gaml.extensions.traffic, is part of the source - * code of the GAMA modeling and simulation platform (v. 1.8) + * PedestrianRoadSkill.java, in miat.gaml.extensions.pedestrian, is part of the source code of the GAMA modeling and + * simulation platform (v.1.8.2). * - * (c) 2007-2018 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -46,6 +46,9 @@ import msi.gaml.types.IType; import msi.gaml.types.Types; +/** + * The Class PedestrianRoadSkill. + */ @skill ( name = PedestrianRoadSkill.PEDESTRIAN_ROAD_SKILL, concept = { IConcept.TRANSPORT, IConcept.SKILL }, @@ -83,92 +86,212 @@ init = "[]", doc = @doc ("The exit hub (several exit connected to each road extremities) that makes it possible to reduce angular distance when travelling to connected pedestrian roads")) }) public class PedestrianRoadSkill extends Skill { - + + /** The Constant PEDESTRIAN_ROAD_SKILL. */ public final static String PEDESTRIAN_ROAD_SKILL = "pedestrian_road"; + + /** The Constant LINKED_PEDESTRIAN_ROADS. */ public final static String LINKED_PEDESTRIAN_ROADS = "linked_pedestrian_roads"; + /** The Constant AGENTS_ON. */ public final static String AGENTS_ON = "agents_on"; + + /** The Constant FREE_SPACE. */ public final static String FREE_SPACE = "free_space"; + + /** The Constant PEDESTRIAN_ROAD_STATUS. */ public final static String PEDESTRIAN_ROAD_STATUS = "road_status"; + + /** The Constant EXIT_NODES_HUB. */ public final static String EXIT_NODES_HUB = "exit_nodes"; + + /** The Constant DISTANCE. */ public final static String DISTANCE = "distance"; + + /** The Constant INTERSECTION_AREAS. */ public final static String INTERSECTION_AREAS = "intersection_areas"; + /** The Constant SIMPLE_STATUS. */ public final static int SIMPLE_STATUS = 0; // use simple goto operator on those road + + /** The Constant COMPLEX_STATUS. */ public final static int COMPLEX_STATUS = 1; // use walk operator + /** + * Gets the agents on. + * + * @param agent + * the agent + * @return the agents on + */ @SuppressWarnings ("unchecked") @getter (AGENTS_ON) public static IList getAgentsOn(final IAgent agent) { return (IList) agent.getAttribute(AGENTS_ON); } + /** + * Gets the linked pedestrian roads. + * + * @param agent + * the agent + * @return the linked pedestrian roads + */ + @SuppressWarnings ("unchecked") @getter (LINKED_PEDESTRIAN_ROADS) public static IList getLinkedPedestrianRoads(final IAgent agent) { return (IList) agent.getAttribute(LINKED_PEDESTRIAN_ROADS); } - + + /** + * Gets the exit nodes hub. + * + * @param agent + * the agent + * @return the exit nodes hub + */ @SuppressWarnings ("unchecked") @getter (EXIT_NODES_HUB) public static IMap> getExitNodesHub(final IAgent agent) { return (IMap>) agent.getAttribute(EXIT_NODES_HUB); } + /** + * Sets the exit nodes hub. + * + * @param agent + * the agent + * @param exitNodesHub + * the exit nodes hub + */ @setter (EXIT_NODES_HUB) public static void setExitNodesHub(final IAgent agent, final IMap> exitNodesHub) { agent.setAttribute(EXIT_NODES_HUB, exitNodesHub); } + /** + * Gets the connected segments intersection. + * + * @param agent + * the agent + * @return the connected segments intersection + */ @SuppressWarnings ("unchecked") @getter (INTERSECTION_AREAS) public static IMap getConnectedSegmentsIntersection(final IAgent agent) { return (IMap) agent.getAttribute(INTERSECTION_AREAS); } + /** + * Sets the connected segments intersection. + * + * @param agent + * the agent + * @param map + * the map + */ @setter (INTERSECTION_AREAS) public static void setConnectedSegmentsIntersection(final IAgent agent, final IMap map) { agent.setAttribute(INTERSECTION_AREAS, map); } + /** + * Gets the pedestrian road status. + * + * @param agent + * the agent + * @return the pedestrian road status + */ @getter (PEDESTRIAN_ROAD_STATUS) public static int getPedestrianRoadStatus(final IAgent agent) { return (int) agent.getAttribute(PEDESTRIAN_ROAD_STATUS); } + /** + * Sets the pedestrian road status. + * + * @param agent + * the agent + * @param status + * the status + */ @setter (PEDESTRIAN_ROAD_STATUS) public static void setPedestrianRoadStatus(final IAgent agent, final int status) { agent.setAttribute(PEDESTRIAN_ROAD_STATUS, status); } + /** + * Gets the free space. + * + * @param agent + * the agent + * @return the free space + */ @getter (FREE_SPACE) public static IShape getFreeSpace(final IAgent agent) { return (IShape) agent.getAttribute(FREE_SPACE); } + /** + * Sets the free space. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (FREE_SPACE) public static void setFreeSpace(final IAgent agent, final IShape val) { agent.setAttribute(FREE_SPACE, val); } + /** + * Sets the distance. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (DISTANCE) public static void setDistance(final IAgent agent, final Double val) { agent.setAttribute(DISTANCE, val); } + /** + * Gets the distance. + * + * @param agent + * the agent + * @return the distance + */ @getter (DISTANCE) public static Double getDistance(final IAgent agent) { return (Double) agent.getAttribute(DISTANCE); } + /** + * Gets the close agents. + * + * @param agent + * the agent + * @return the close agents + */ public static IList getCloseAgents(final IAgent agent) { IList agents = GamaListFactory.create(); agents.addAll(getAgentsOn(agent)); - for (IAgent ag : getLinkedPedestrianRoads(agent)) { - agents.addAll(getAgentsOn(ag)); - } + for (IAgent ag : getLinkedPedestrianRoads(agent)) { agents.addAll(getAgentsOn(ag)); } return agents; } + /** + * Prim initialize. + * + * @param scope + * the scope + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = "initialize", args = { @arg ( @@ -210,12 +333,13 @@ public static IList getCloseAgents(final IAgent agent) { value = "action to initialize the free space of roads", examples = { @example ("do initialize distance: 10.0 obstacles: [building];") })) @SuppressWarnings ("unchecked") - public void primInitialize(final IScope scope) throws GamaRuntimeException { + public boolean primInitialize(final IScope scope) throws GamaRuntimeException { final IAgent agent = getCurrentAgent(scope); int status = scope.hasArg("status") ? scope.getIntArg("status") : agent.getGeometry().hasAttribute(PEDESTRIAN_ROAD_STATUS) ? GamaIntegerType.staticCast(scope, - agent.getGeometry().getAttribute(PEDESTRIAN_ROAD_STATUS), null, false) : 1; + agent.getGeometry().getAttribute(PEDESTRIAN_ROAD_STATUS), null, false) + : 1; setPedestrianRoadStatus(agent, status); double distAdd = scope.hasArg("distance_extremity") ? scope.getFloatArg("distance_extremity") : 0.0; IShape freeSpace = agent.getGeometry().copy(scope); @@ -272,7 +396,7 @@ public void primInitialize(final IScope scope) throws GamaRuntimeException { IShape g = Spatial.Operators.inter(scope, freeSpace, bds); if (g != null) { freeSpace = g; } } - if (freeSpace == null) return ; + if (freeSpace == null) return false; if (freeSpace.getGeometries().size() > 1) { for (IShape g : freeSpace.getGeometries()) { if (agent.intersects(g)) { @@ -297,9 +421,7 @@ public void primInitialize(final IScope scope) throws GamaRuntimeException { obstacles.addAll((Collection) species.getPopulations(scope)); } } else { - for (Object obj : maskedbyL) { - if (obj instanceof IShape) { obstacles.add((IShape) obj); } - } + for (Object obj : maskedbyL) { if (obj instanceof IShape) { obstacles.add((IShape) obj); } } } freeSpace = Operators.masked_by(scope, freeSpace, obstacles, prec); } @@ -308,8 +430,15 @@ public void primInitialize(final IScope scope) throws GamaRuntimeException { } setFreeSpace(agent, freeSpace); + return true; } + /** + * Prim intersection areas. + * + * @param scope + * the scope + */ @action ( name = "build_intersection_areas", args = { @arg ( @@ -320,15 +449,16 @@ public void primInitialize(final IScope scope) throws GamaRuntimeException { doc = @doc ( value = "Build intersection areas with connected roads", examples = { @example ("do build_intersection_areas pedestrian_graph: pedestrian_network;") })) - public void primIntersectionAreas(final IScope scope) { + public boolean primIntersectionAreas(final IScope scope) { final IAgent agent = getCurrentAgent(scope); if (!agent.isInstanceOf(PEDESTRIAN_ROAD_SKILL, true)) throw GamaRuntimeException .error("Trying to manipulate agent with " + PEDESTRIAN_ROAD_SKILL + " while being " + agent, scope); IShape g = PedestrianRoadSkill.getFreeSpace(agent); - final IGraph graph = (IGraph) scope.getVarValue(PedestrianSkill.PEDESTRIAN_GRAPH); + @SuppressWarnings ("unchecked") final IGraph graph = + (IGraph) scope.getVarValue(PedestrianSkill.PEDESTRIAN_GRAPH); IMap connectedComp = GamaMapFactory.create(); - IShape target = (IShape) graph.getEdgeTarget(agent); - IShape source = (IShape) graph.getEdgeSource(agent); + IShape target = graph.getEdgeTarget(agent); + IShape source = graph.getEdgeSource(agent); IList connectedRoads = getLinkedPedestrianRoads(agent); for (Object obj : graph.outgoingEdgesOf(source)) { IAgent ag = (IAgent) obj; @@ -355,8 +485,15 @@ public void primIntersectionAreas(final IScope scope) { } PedestrianRoadSkill.setConnectedSegmentsIntersection(agent, connectedComp); + return true; } + /** + * Prim exit hub escape. + * + * @param scope + * the scope + */ @action ( name = "build_exit_hub", args = { @arg ( @@ -373,7 +510,7 @@ public void primIntersectionAreas(final IScope scope) { value = "Add exit hub to pedestrian corridor to reduce angular distance between node of the network", examples = { @example ("do build_exit_hub pedestrian_graph: pedestrian_network distance_between_targets: 10.0;") })) - public void primExitHubEscape(final IScope scope) { + public boolean primExitHubEscape(final IScope scope) { // TODO : Exit hub should probably be symmetric ... final IAgent agent = getCurrentAgent(scope); @@ -399,7 +536,7 @@ public void primExitHubEscape(final IScope scope) { } } PedestrianRoadSkill.setExitNodesHub(agent, exitHub); - + return true; } /** @@ -434,16 +571,12 @@ public static int getRoadStatus(final IScope scope, final IShape road) { @SuppressWarnings ("unchecked") public static IList getConnectedOutput(final IScope scope, final IShape currentRoad, final GamaPoint target) { - if (currentRoad.hasAttribute(EXIT_NODES_HUB)) { - IMap> exitHub = - (IMap>) currentRoad.getAttribute(EXIT_NODES_HUB); - if (exitHub.containsKey(target)) - return exitHub.get(target); - else - return GamaListFactory.create(Types.POINT, Stream.of(target)); - } else - throw GamaRuntimeException.error("Looking for exit hub related to " + currentRoad + " but there is none", - scope); + if (!currentRoad.hasAttribute(EXIT_NODES_HUB)) throw GamaRuntimeException + .error("Looking for exit hub related to " + currentRoad + " but there is none", scope); + IMap> exitHub = + (IMap>) currentRoad.getAttribute(EXIT_NODES_HUB); + if (exitHub.containsKey(target)) return exitHub.get(target); + return GamaListFactory.create(Types.POINT, Stream.of(target)); } /** @@ -470,14 +603,32 @@ public static void register(final IScope scope, final IAgent road, final IAgent * @param pedestrian */ @SuppressWarnings ("unchecked") - public static void unregister(final IScope scope, final IAgent road, final IAgent pedestrian) { + public static boolean unregister(final IScope scope, final IAgent road, final IAgent pedestrian) { ((IList) road.getAttribute(AGENTS_ON)).remove(pedestrian); pedestrian.setAttribute("current_edge", null); + return true; } + /** + * Connected roads. + * + * @param scope + * the scope + * @param currentRoad + * the current road + * @param dist + * the dist + * @param lp + * the lp + * @param pp + * the pp + * @param bounds + * the bounds + * @return the i list + */ /* * Create exit hub for a set of connected out edges - */ + */ @SuppressWarnings ("unchecked") private IList connectedRoads(final IScope scope, final IAgent currentRoad, final Double dist, final GamaPoint lp, final GamaPoint pp, final IShape bounds) { diff --git a/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianSkill.java b/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianSkill.java index ad760ce464..cb7bf4ae0f 100644 --- a/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianSkill.java +++ b/miat.gaml.extensions.pedestrian/src/miat/gaml/extensions/skills/PedestrianSkill.java @@ -1,3 +1,13 @@ +/******************************************************************************************************* + * + * PedestrianSkill.java, in miat.gaml.extensions.pedestrian, is part of the source code of the GAMA modeling and + * simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package miat.gaml.extensions.skills; import msi.gama.common.interfaces.IKeyword; @@ -41,6 +51,9 @@ import msi.gaml.types.IType; import msi.gaml.types.Types; +/** + * The Class PedestrianSkill. + */ @skill ( name = "pedestrian", concept = { IConcept.TRANSPORT, IConcept.SKILL }, @@ -200,329 +213,812 @@ public class PedestrianSkill extends MovingSkill { // ---------- CONSTANTS -------------- // + /** The Constant PEDESTRIAN_MODEL. */ // General mode of walking public final static String PEDESTRIAN_MODEL = "pedestrian_model"; + /** The Constant SHOULDER_LENGTH. */ public final static String SHOULDER_LENGTH = "shoulder_length"; + + /** The Constant MINIMAL_DISTANCE. */ public final static String MINIMAL_DISTANCE = "minimal_distance"; + /** The Constant CURRENT_TARGET. */ public final static String CURRENT_TARGET = "current_waypoint"; + + /** The Constant OBSTACLE_CONSIDERATION_DISTANCE. */ public final static String OBSTACLE_CONSIDERATION_DISTANCE = "obstacle_consideration_distance"; + + /** The Constant PEDESTRIAN_CONSIDERATION_DISTANCE. */ public final static String PEDESTRIAN_CONSIDERATION_DISTANCE = "pedestrian_consideration_distance"; + + /** The Constant PROBA_DETOUR. */ public final static String PROBA_DETOUR = "proba_detour"; + + /** The Constant AVOID_OTHER. */ public final static String AVOID_OTHER = "avoid_other"; + + /** The Constant OBSTACLE_SPECIES. */ public final static String OBSTACLE_SPECIES = "obstacle_species"; + + /** The Constant PEDESTRIAN_SPECIES. */ public final static String PEDESTRIAN_SPECIES = "pedestrian_species"; + + /** The Constant VELOCITY. */ public final static String VELOCITY = "velocity"; + + /** The Constant FORCES. */ public final static String FORCES = "forces"; + /** The Constant A_PEDESTRIAN_SFM. */ public final static String A_PEDESTRIAN_SFM = "A_pedestrians_SFM"; + + /** The Constant A_OBSTACLES_SFM. */ public final static String A_OBSTACLES_SFM = "A_obstacles_SFM"; + + /** The Constant B_PEDESTRIAN_SFM. */ public final static String B_PEDESTRIAN_SFM = "B_pedestrians_SFM"; + + /** The Constant B_OBSTACLES_SFM. */ public final static String B_OBSTACLES_SFM = "B_obstacles_SFM"; + /** The Constant K_SFM. */ public final static String K_SFM = "k_SFM"; + + /** The Constant KAPPA_SFM. */ public final static String KAPPA_SFM = "kappa_SFM"; + + /** The Constant RELAXION_SFM. */ public final static String RELAXION_SFM = "relaxion_SFM"; + + /** The Constant GAMA_SFM. */ public final static String GAMA_SFM = "gama_SFM"; + + /** The Constant lAMBDA_SFM. */ public final static String lAMBDA_SFM = "lambda_SFM"; + /** The Constant N_SFM. */ public final static String N_SFM = "n_SFM"; + + /** The Constant N_PRIME_SFM. */ public final static String N_PRIME_SFM = "n_prime_SFM"; + /** The Constant CURRENT_TARGET_GEOM. */ public final static String CURRENT_TARGET_GEOM = "current_waypoint_geom"; + + /** The Constant CURRENT_INDEX. */ public final static String CURRENT_INDEX = "current_index"; + + /** The Constant FINAL_TARGET. */ public final static String FINAL_TARGET = "final_waypoint"; + + /** The Constant CURRENT_PATH. */ public final static String CURRENT_PATH = "current_path"; + + /** The Constant PEDESTRIAN_GRAPH. */ public final static String PEDESTRIAN_GRAPH = "pedestrian_graph"; + + /** The Constant TOLERANCE_TARGET. */ public final static String TOLERANCE_TARGET = "tolerance_waypoint"; + /** The Constant USE_GEOMETRY_TARGET. */ public final static String USE_GEOMETRY_TARGET = "use_geometry_waypoint"; + /** The Constant COMPUTE_VIRTUAL_PATH. */ // ACTION public final static String COMPUTE_VIRTUAL_PATH = "compute_virtual_path"; + + /** The Constant WALK. */ public final static String WALK = "walk"; + + /** The Constant WALK_TO. */ public final static String WALK_TO = "walk_to"; // ---------- VARIABLES GETTER AND SETTER ------------- // + /** The Constant TARGETS. */ public final static String TARGETS = "waypoints"; + + /** The Constant ROADS_TARGET. */ public final static String ROADS_TARGET = "roads_waypoints"; + /** + * Gets the shoulder length. + * + * @param agent + * the agent + * @return the shoulder length + */ @getter (SHOULDER_LENGTH) public double getShoulderLength(final IAgent agent) { return (Double) agent.getAttribute(SHOULDER_LENGTH); } + /** + * Gets the forces. + * + * @param agent + * the agent + * @return the forces + */ + @SuppressWarnings ("unchecked") @getter (FORCES) public IMap getForces(final IAgent agent) { return (IMap) agent.getAttribute(FORCES); } + /** + * Sets the shoulder length. + * + * @param agent + * the agent + * @param s + * the s + */ @setter (SHOULDER_LENGTH) public void setShoulderLength(final IAgent agent, final double s) { agent.setAttribute(SHOULDER_LENGTH, s); } + /** + * Gets the min dist. + * + * @param agent + * the agent + * @return the min dist + */ @getter (MINIMAL_DISTANCE) public double getMinDist(final IAgent agent) { return (Double) agent.getAttribute(MINIMAL_DISTANCE); } + /** + * Sets the min dist. + * + * @param agent + * the agent + * @param s + * the s + */ @setter (MINIMAL_DISTANCE) public void setMinDist(final IAgent agent, final double s) { agent.setAttribute(MINIMAL_DISTANCE, s); } + /** + * Gets the ksfm. + * + * @param agent + * the agent + * @return the ksfm + */ @getter (K_SFM) public double getKSFM(final IAgent agent) { return (Double) agent.getAttribute(K_SFM); } + /** + * Sets the KSFM. + * + * @param agent + * the agent + * @param s + * the s + */ @setter (K_SFM) public void setKSFM(final IAgent agent, final double s) { agent.setAttribute(K_SFM, s); } + /** + * Gets the kappa SFM. + * + * @param agent + * the agent + * @return the kappa SFM + */ @getter (KAPPA_SFM) public double getKappaSFM(final IAgent agent) { return (Double) agent.getAttribute(KAPPA_SFM); } + /** + * Sets the kappa SFM. + * + * @param agent + * the agent + * @param s + * the s + */ @setter (KAPPA_SFM) public void setKappaSFM(final IAgent agent, final double s) { agent.setAttribute(KAPPA_SFM, s); } + /** + * Sets the N PRIM E SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (N_PRIME_SFM) public void setN_PRIME_SFM(final IAgent agent, final Double val) { agent.setAttribute(N_PRIME_SFM, val); } + /** + * Gets the n prime sfm. + * + * @param agent + * the agent + * @return the n prime sfm + */ @getter (N_PRIME_SFM) public Double getN_PRIME_SFM(final IAgent agent) { return (Double) agent.getAttribute(N_PRIME_SFM); } + /** + * Sets the N SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (N_SFM) public void setN_SFM(final IAgent agent, final Double val) { agent.setAttribute(N_SFM, val); } + /** + * Gets the n sfm. + * + * @param agent + * the agent + * @return the n sfm + */ @getter (N_SFM) public Double getN_SFM(final IAgent agent) { return (Double) agent.getAttribute(N_SFM); } + /** + * Gets the obstacle species. + * + * @param agent + * the agent + * @return the obstacle species + */ + @SuppressWarnings ("unchecked") @getter (OBSTACLE_SPECIES) public GamaList getObstacleSpecies(final IAgent agent) { return (GamaList) agent.getAttribute(OBSTACLE_SPECIES); } + /** + * Sets the obstacle species. + * + * @param agent + * the agent + * @param os + * the os + */ @setter (OBSTACLE_SPECIES) public void setObstacleSpecies(final IAgent agent, final GamaList os) { agent.setAttribute(OBSTACLE_SPECIES, os); } + /** + * Gets the pedestrian species. + * + * @param agent + * the agent + * @return the pedestrian species + */ + @SuppressWarnings ("unchecked") @getter (PEDESTRIAN_SPECIES) public GamaList getPedestrianSpecies(final IAgent agent) { return (GamaList) agent.getAttribute(PEDESTRIAN_SPECIES); } + /** + * Sets the pedestrian species. + * + * @param agent + * the agent + * @param os + * the os + */ @setter (PEDESTRIAN_SPECIES) public void setPedestrianSpecies(final IAgent agent, final GamaList os) { agent.setAttribute(PEDESTRIAN_SPECIES, os); } + /** + * Gets the current target. + * + * @param agent + * the agent + * @return the current target + */ @getter (CURRENT_TARGET) public IShape getCurrentTarget(final IAgent agent) { return (IShape) agent.getAttribute(CURRENT_TARGET); } + /** + * Sets the current target. + * + * @param agent + * the agent + * @param point + * the point + */ @setter (CURRENT_TARGET) public void setCurrentTarget(final IAgent agent, final IShape point) { agent.setAttribute(CURRENT_TARGET, point); } + /** + * Gets the obstacle consideration distance. + * + * @param agent + * the agent + * @return the obstacle consideration distance + */ @getter (OBSTACLE_CONSIDERATION_DISTANCE) public Double getObstacleConsiderationDistance(final IAgent agent) { return (Double) agent.getAttribute(OBSTACLE_CONSIDERATION_DISTANCE); } + /** + * Sets the obstacle consideration distance. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (OBSTACLE_CONSIDERATION_DISTANCE) public void setObstacleConsiderationDistance(final IAgent agent, final Double val) { agent.setAttribute(OBSTACLE_CONSIDERATION_DISTANCE, val); } + /** + * Gets the pedestrian consideration distance. + * + * @param agent + * the agent + * @return the pedestrian consideration distance + */ @getter (PEDESTRIAN_CONSIDERATION_DISTANCE) public Double getPedestrianConsiderationDistance(final IAgent agent) { return (Double) agent.getAttribute(PEDESTRIAN_CONSIDERATION_DISTANCE); } + /** + * Sets the pedestrian consideration distance. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (PEDESTRIAN_CONSIDERATION_DISTANCE) public void setPedestrianConsiderationDistance(final IAgent agent, final Double val) { agent.setAttribute(PEDESTRIAN_CONSIDERATION_DISTANCE, val); } + /** + * Gets the proba detour. + * + * @param agent + * the agent + * @return the proba detour + */ @getter (PROBA_DETOUR) public Double getProbaDetour(final IAgent agent) { return (Double) agent.getAttribute(PROBA_DETOUR); } + /** + * Setl AMBD A SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (lAMBDA_SFM) public void setlAMBDA_SFM(final IAgent agent, final Double val) { agent.setAttribute(lAMBDA_SFM, val); } + /** + * Gets the l AMBD A SFM. + * + * @param agent + * the agent + * @return the l AMBD A SFM + */ @getter (lAMBDA_SFM) public Double getlAMBDA_SFM(final IAgent agent) { return (Double) agent.getAttribute(lAMBDA_SFM); } + /** + * Sets the GAM A SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (GAMA_SFM) public void setGAMA_SFM(final IAgent agent, final Double val) { agent.setAttribute(GAMA_SFM, val); } + /** + * Gets the gama sfm. + * + * @param agent + * the agent + * @return the gama sfm + */ @getter (GAMA_SFM) public Double getGAMA_SFM(final IAgent agent) { return (Double) agent.getAttribute(GAMA_SFM); } + /** + * Sets the proba detour. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (PROBA_DETOUR) public void setProbaDetour(final IAgent agent, final Double val) { agent.setAttribute(PROBA_DETOUR, val); } + /** + * Gets the relaxion sfm. + * + * @param agent + * the agent + * @return the relaxion sfm + */ @getter (RELAXION_SFM) public Double getRELAXION_SFM(final IAgent agent) { return (Double) agent.getAttribute(RELAXION_SFM); } + /** + * Sets the RELAXIO N SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (RELAXION_SFM) public void setRELAXION_SFM(final IAgent agent, final Double val) { agent.setAttribute(RELAXION_SFM, val); } + /** + * Gets the a pedestrian SFM. + * + * @param agent + * the agent + * @return the a pedestrian SFM + */ @getter (A_PEDESTRIAN_SFM) public Double getAPedestrian_SFM(final IAgent agent) { return (Double) agent.getAttribute(A_PEDESTRIAN_SFM); } + /** + * Sets the A pedestrian SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (A_PEDESTRIAN_SFM) public void setAPedestrian_SFM(final IAgent agent, final Double val) { agent.setAttribute(A_PEDESTRIAN_SFM, val); } + /** + * Gets the a obst SFM. + * + * @param agent + * the agent + * @return the a obst SFM + */ @getter (A_OBSTACLES_SFM) public Double getAObstSFM(final IAgent agent) { return (Double) agent.getAttribute(A_OBSTACLES_SFM); } + /** + * Sets the A obst SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (A_OBSTACLES_SFM) public void setAObstSFM(final IAgent agent, final Double val) { agent.setAttribute(A_OBSTACLES_SFM, val); } + /** + * Gets the b sfm. + * + * @param agent + * the agent + * @return the b sfm + */ @getter (B_PEDESTRIAN_SFM) public Double getB_SFM(final IAgent agent) { return (Double) agent.getAttribute(B_PEDESTRIAN_SFM); } + /** + * Sets the B SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (B_PEDESTRIAN_SFM) public void setB_SFM(final IAgent agent, final Double val) { agent.setAttribute(B_PEDESTRIAN_SFM, val); } + /** + * Gets the b obst SFM. + * + * @param agent + * the agent + * @return the b obst SFM + */ @getter (B_OBSTACLES_SFM) public Double getBObstSFM(final IAgent agent) { return (Double) agent.getAttribute(B_OBSTACLES_SFM); } + /** + * Sets the B obst SFM. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (B_OBSTACLES_SFM) public void setBObstSFM(final IAgent agent, final Double val) { agent.setAttribute(B_OBSTACLES_SFM, val); } + /** + * Gets the avoid other. + * + * @param agent + * the agent + * @return the avoid other + */ @getter (AVOID_OTHER) public Boolean getAvoidOther(final IAgent agent) { return (Boolean) agent.getAttribute(AVOID_OTHER); } + /** + * Sets the avoid other. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (AVOID_OTHER) public void setAvoidOther(final IAgent agent, final Boolean val) { agent.setAttribute(AVOID_OTHER, val); } + /** + * Sets the velocity. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (VELOCITY) public void setVelocity(final IAgent agent, final GamaPoint val) { agent.setAttribute(VELOCITY, val); } + /** + * Gets the velocity. + * + * @param agent + * the agent + * @return the velocity + */ @getter (VELOCITY) public GamaPoint getVelocity(final IAgent agent) { return (GamaPoint) agent.getAttribute(VELOCITY); } + /** + * Gets the tolerance target. + * + * @param agent + * the agent + * @return the tolerance target + */ @getter (TOLERANCE_TARGET) public double getToleranceTarget(final IAgent agent) { return (Double) agent.getAttribute(TOLERANCE_TARGET); } + /** + * Sets the tolerance target. + * + * @param agent + * the agent + * @param s + * the s + */ @setter (TOLERANCE_TARGET) public void setToleranceTarget(final IAgent agent, final double s) { agent.setAttribute(TOLERANCE_TARGET, s); } + /** + * Gets the targets. + * + * @param agent + * the agent + * @return the targets + */ + @SuppressWarnings ("unchecked") @getter (TARGETS) public IList getTargets(final IAgent agent) { return (IList) agent.getAttribute(TARGETS); } + /** + * Gets the roads targets. + * + * @param agent + * the agent + * @return the roads targets + */ @getter (ROADS_TARGET) public IMap getRoadsTargets(final IAgent agent) { return (IMap) agent.getAttribute(ROADS_TARGET); } + /** + * Sets the targets. + * + * @param agent + * the agent + * @param points + * the points + */ @setter (TARGETS) public void setTargets(final IAgent agent, final IList points) { agent.setAttribute(TARGETS, points); } + /** + * Gets the final target. + * + * @param agent + * the agent + * @return the final target + */ @getter (FINAL_TARGET) public IShape getFinalTarget(final IAgent agent) { return (IShape) agent.getAttribute(FINAL_TARGET); } + /** + * Sets the final target. + * + * @param agent + * the agent + * @param point + * the point + */ @setter (FINAL_TARGET) public void setFinalTarget(final IAgent agent, final IShape point) { agent.setAttribute(FINAL_TARGET, point); } + /** + * Gets the current index. + * + * @param agent + * the agent + * @return the current index + */ @getter (CURRENT_INDEX) public Integer getCurrentIndex(final IAgent agent) { return (Integer) agent.getAttribute(CURRENT_INDEX); } + /** + * Sets the current index. + * + * @param agent + * the agent + * @param index + * the index + */ @setter (CURRENT_INDEX) public void setCurrentIndex(final IAgent agent, final Integer index) { agent.setAttribute(CURRENT_INDEX, index); } + /** + * Gets the use geometry target. + * + * @param agent + * the agent + * @return the use geometry target + */ @getter (USE_GEOMETRY_TARGET) public Boolean getUseGeometryTarget(final IAgent agent) { return (Boolean) agent.getAttribute(USE_GEOMETRY_TARGET); } + /** + * Sets the use geometry target. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (USE_GEOMETRY_TARGET) public void setUseGeometryTarget(final IAgent agent, final Boolean val) { agent.setAttribute(USE_GEOMETRY_TARGET, val); } + /** + * Gets the pedestrian model. + * + * @param agent + * the agent + * @return the pedestrian model + */ @getter (PEDESTRIAN_MODEL) public String getPedestrianModel(final IAgent agent) { return (String) agent.getAttribute(PEDESTRIAN_MODEL); } + /** + * Sets the pedestrian model. + * + * @param agent + * the agent + * @param val + * the val + */ @setter (PEDESTRIAN_MODEL) public void setPedestrianModel(final IAgent agent, final String val) { if ("advanced".equals(val) || "simple".equals(val)) { @@ -536,6 +1032,14 @@ public void setPedestrianModel(final IAgent agent, final String val) { // ----------------------------------- // + /** + * Prim walk to. + * + * @param scope + * the scope + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = WALK_TO, args = { @arg ( @@ -554,18 +1058,18 @@ public void setPedestrianModel(final IAgent agent, final String val) { doc = @doc ( value = "action to walk toward a target", examples = { @example ("do walk_to {10,10};") })) - public void primWalkTo(final IScope scope) throws GamaRuntimeException { + public boolean primWalkTo(final IScope scope) throws GamaRuntimeException { final IAgent agent = getCurrentAgent(scope); - if (agent == null || agent.dead()) return; + if (agent == null || agent.dead()) return false; IShape goal = computeTarget(scope, agent); - if (goal == null) return; + if (goal == null) return false; IShape bounds = null; if (scope.hasArg(IKeyword.BOUNDS)) { final Object obj = scope.getArg(IKeyword.BOUNDS, IType.NONE); bounds = GamaGeometryType.staticCast(scope, obj, null, false); } IList speciesList = getObstacleSpecies(agent); - IContainer obstacles = null; + IContainer obstacles = null; if (speciesList.size() == 1) { obstacles = speciesList.get(0); } else { @@ -577,7 +1081,7 @@ public void primWalkTo(final IScope scope) throws GamaRuntimeException { } speciesList = getPedestrianSpecies(agent); - IContainer pedestrians = null; + IContainer pedestrians = null; if (speciesList.size() == 1) { pedestrians = speciesList.get(0); } else { @@ -594,7 +1098,7 @@ public void primWalkTo(final IScope scope) throws GamaRuntimeException { obstacles, maxDist); setRealSpeed(agent, realSpeed); - + return true; } /** @@ -673,7 +1177,8 @@ public double walkWithForceModel(final IScope scope, final IAgent agent, final I } double realSpeed = 0.0; double proba_detour = getProbaDetour(agent); - if ((!Random.opFlip(scope, 1.0 - proba_detour) || (location.euclidianDistanceTo(target) <= agent.getLocation().euclidianDistanceTo(target)))) { + if (!Random.opFlip(scope, 1.0 - proba_detour) + || location.euclidianDistanceTo(target) <= agent.getLocation().euclidianDistanceTo(target)) { realSpeed = agent.euclidianDistanceTo(location) / scope.getSimulation().getTimeStep(scope); setVelocity(agent, location.copy(scope).minus(getLocation(agent))); setLocation(agent, location); @@ -701,18 +1206,18 @@ public GamaPoint avoidSFMSimple(final IScope scope, final IAgent agent, final Ga final GamaPoint currentTarget, final double distPercepPedestrian, final double distPercepObstacle, final IContainer pedestriansList, final IContainer obstaclesList) { IMap forcesMap = GamaMapFactory.create(); - + GamaPoint current_velocity = getVelocity(agent).copy(scope); GamaPoint fsoc = new GamaPoint(0, 0, 0); double dist = location.euclidianDistanceTo(currentTarget); - double step = scope.getSimulation().getClock().getStepInSeconds(); - double speed = getSpeed(agent); + // double step = scope.getSimulation().getClock().getStepInSeconds(); + // double speed = getSpeed(agent); IList obstacles = GamaListFactory.create(Types.AGENT); IList pedestrians = GamaListFactory.create(Types.AGENT); pedestrians.addAll(Spatial.Queries.at_distance(scope, pedestriansList, distPercepPedestrian)); obstacles.addAll(Spatial.Queries.at_distance(scope, obstaclesList, distPercepObstacle)); - + pedestrians.remove(agent); pedestrians.removeIf(IAgent::dead); double lambda = getlAMBDA_SFM(agent); @@ -752,19 +1257,38 @@ public GamaPoint avoidSFMSimple(final IScope scope, final IAgent agent, final Ga forcesMap.put(ag, force); } - - + GamaPoint desiredVelo = currentTarget.copy(scope).minus(location) .divideBy(dist / Math.min(getSpeed(agent), dist / scope.getSimulation().getClock().getStepInSeconds())); GamaPoint fdest = desiredVelo.minus(current_velocity).dividedBy(getRELAXION_SFM(agent)); - forcesMap.put(agent, fdest); agent.setAttribute(FORCES, forcesMap); GamaPoint forces = fdest.add(fsoc); return current_velocity.add(forces).normalize(); } + /** + * Avoid SFM. + * + * @param scope + * the scope + * @param agent + * the agent + * @param location + * the location + * @param currentTarget + * the current target + * @param distPercepPedestrian + * the dist percep pedestrian + * @param distPercepObstacle + * the dist percep obstacle + * @param pedestriansList + * the pedestrians list + * @param obstaclesList + * the obstacles list + * @return the gama point + */ public GamaPoint avoidSFM(final IScope scope, final IAgent agent, final GamaPoint location, final GamaPoint currentTarget, final double distPercepPedestrian, final double distPercepObstacle, final IContainer pedestriansList, final IContainer obstaclesList) { @@ -871,6 +1395,15 @@ public GamaPoint avoidSFM(final IScope scope, final IAgent agent, final GamaPoin return current_velocity.add(forces).normalize(); } + /** + * Prim compute virtual path. + * + * @param scope + * the scope + * @return the i path + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = COMPUTE_VIRTUAL_PATH, args = { @arg ( @@ -903,7 +1436,7 @@ public IPath primComputeVirtualPath(final IScope scope) throws GamaRuntimeExcept IMap roadTarget = GamaMapFactory.create(); IList targets = GamaListFactory.create(); IList segments = thePath.getEdgeGeometry(); - GamaPoint pp = source.getCentroid(); + // GamaPoint pp = source.getCentroid(); for (int i = 0; i < segments.size(); i++) { IShape cSeg = segments.get(i); @@ -916,12 +1449,13 @@ public IPath primComputeVirtualPath(final IScope scope) throws GamaRuntimeExcept if (i < segments.size() - 1) { cRoadNext = thePath.getRealObject(segments.get(i + 1)); geomNext = PedestrianRoadSkill.getFreeSpace(cRoadNext.getAgent()); - } else { - geomNext = null; } + // else { + // geomNext = null; + // } } - IShape nSeg = i == segments.size() - 1 ? null : segments.get(i + 1); + // IShape nSeg = i == segments.size() - 1 ? null : segments.get(i + 1); // AD Note: getPoints() can be a very costly operation. It'd be better to call it once. for (int j = 1; j < cSeg.getPoints().size(); j++) { GamaPoint pt = cSeg.getPoints().get(j); @@ -929,12 +1463,12 @@ public IPath primComputeVirtualPath(final IScope scope) throws GamaRuntimeExcept if (PedestrianRoadSkill.getRoadStatus(scope, cRoad) == PedestrianRoadSkill.SIMPLE_STATUS) { cTarget = pt; } else { - GamaPoint nextPt = null; - if (j == cSeg.getPoints().size() - 1) { - nextPt = nSeg == null ? null : nSeg.getPoints().get(1); - } else { - nextPt = cSeg.getPoints().get(j + 1); - } + // GamaPoint nextPt = null; + // if (j == cSeg.getPoints().size() - 1) { + // nextPt = nSeg == null ? null : nSeg.getPoints().get(1); + // } else { + // nextPt = cSeg.getPoints().get(j + 1); + // } cTarget = pt; if (cTarget == null) { cTarget = pt; } } @@ -954,7 +1488,7 @@ public IPath primComputeVirtualPath(final IScope scope) throws GamaRuntimeExcept targets.add(cTarget); roadTarget.put(cTarget, cRoad); - pp = cTarget.getLocation(); + // pp = cTarget.getLocation(); } } IShape targ = targets.get(0); @@ -983,6 +1517,14 @@ public IPath primComputeVirtualPath(final IScope scope) throws GamaRuntimeExcept return thePath; } + /** + * Prim arrived at destination. + * + * @param scope + * the scope + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = "release_path", args = { @arg ( @@ -992,7 +1534,7 @@ public IPath primComputeVirtualPath(final IScope scope) throws GamaRuntimeExcept doc = @doc ("current road on which the agent is located (can be nil)")), }, doc = @doc ( value = "clean all the interne state of the agent")) - public void primArrivedAtDestination(final IScope scope) throws GamaRuntimeException { + public boolean primArrivedAtDestination(final IScope scope) throws GamaRuntimeException { final IAgent agent = getCurrentAgent(scope); IAgent road = (IAgent) scope.getArg("current_road", IType.AGENT); setCurrentIndex(agent, 0); @@ -1002,23 +1544,32 @@ public void primArrivedAtDestination(final IScope scope) throws GamaRuntimeExcep setCurrentPath(agent, null); setCurrentEdge(agent, (IShape) null); setRealSpeed(agent, 0.0); - if (road != null) { PedestrianRoadSkill.unregister(scope, road, agent); } + if (road != null) return PedestrianRoadSkill.unregister(scope, road, agent); + return false; } + /** + * Prim walk. + * + * @param scope + * the scope + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = WALK, doc = @doc ( value = "action to walk toward the final target using the current_path (requires to use the " + COMPUTE_VIRTUAL_PATH + " action before)", examples = { @example ("do walk;") })) - public void primWalk(final IScope scope) throws GamaRuntimeException { + public boolean primWalk(final IScope scope) throws GamaRuntimeException { final IAgent agent = getCurrentAgent(scope); - if (agent == null || agent.dead()) return; + if (agent == null || agent.dead()) return false; final IShape finalTarget = getFinalTarget(agent); - if (finalTarget == null) return; + if (finalTarget == null) return false; final IList targets = getTargets(agent); - if (targets == null || targets.isEmpty()) return; + if (targets == null || targets.isEmpty()) return false; GamaPoint location = getLocation(agent).copy(scope); double maxDist = computeDistance(scope, agent); @@ -1047,6 +1598,8 @@ public void primWalk(final IScope scope) throws GamaRuntimeException { road == null ? GamaListFactory.create() : PedestrianRoadSkill.getCloseAgents(road); IList speciesList = getObstacleSpecies(agent); IContainer obstacles = null; + + // AD : recreating these lists everytime is really terrible. Better use MetaPopulations if (speciesList.size() == 1) { obstacles = speciesList.get(0); } else { @@ -1087,9 +1640,28 @@ public void primWalk(final IScope scope) throws GamaRuntimeException { } } } - + return true; } + /** + * Arrived at target. + * + * @param scope + * the scope + * @param location + * the location + * @param currentTarget + * the current target + * @param size + * the size + * @param index + * the index + * @param maxIndex + * the max index + * @param targets + * the targets + * @return true, if successful + */ boolean arrivedAtTarget(final IScope scope, final GamaPoint location, final IShape currentTarget, final double size, final int index, final int maxIndex, final IList targets) { double dist = location.euclidianDistanceTo(currentTarget); diff --git a/msi.gama.application/.classpath b/msi.gama.application/.classpath index a9f7ed1a9e..c6b1f7d01d 100644 --- a/msi.gama.application/.classpath +++ b/msi.gama.application/.classpath @@ -1,6 +1,6 @@ - + diff --git a/msi.gama.application/.settings/org.eclipse.jdt.core.prefs b/msi.gama.application/.settings/org.eclipse.jdt.core.prefs index 41a0c24cd2..8a1962f0b0 100644 --- a/msi.gama.application/.settings/org.eclipse.jdt.core.prefs +++ b/msi.gama.application/.settings/org.eclipse.jdt.core.prefs @@ -1,5 +1,13 @@ eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=17 +org.eclipse.jdt.core.compiler.compliance=17 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=enabled +org.eclipse.jdt.core.compiler.source=17 org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=do not insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=do not insert org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=do not insert diff --git a/msi.gama.application/src/msi/gama/application/workbench/GamaActionBarAdvisor.java b/msi.gama.application/src/msi/gama/application/workbench/GamaActionBarAdvisor.java index 3979f699e8..5261561de7 100644 --- a/msi.gama.application/src/msi/gama/application/workbench/GamaActionBarAdvisor.java +++ b/msi.gama.application/src/msi/gama/application/workbench/GamaActionBarAdvisor.java @@ -1,6 +1,17 @@ +/******************************************************************************************************* + * + * GamaActionBarAdvisor.java, in msi.gama.application, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.application.workbench; import java.util.List; + import org.eclipse.core.runtime.Platform; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.ActionContributionItem; @@ -31,35 +42,70 @@ import org.eclipse.ui.menus.CommandContributionItem; import org.eclipse.ui.menus.CommandContributionItemParameter; +/** + * The Class GamaActionBarAdvisor. + */ public class GamaActionBarAdvisor extends ActionBarAdvisor { + /** The window. */ final IWorkbenchWindow window; // generic actions + /** The hide show editor action. */ private IWorkbenchAction hideShowEditorAction; + + /** The close action. */ private IWorkbenchAction closeAction; + + /** The close all action. */ private IWorkbenchAction closeAllAction; + + /** The save action. */ private IWorkbenchAction saveAction; + + /** The save all action. */ private IWorkbenchAction saveAllAction; + + /** The help contents action. */ private IWorkbenchAction helpContentsAction; + + /** The about action. */ private IWorkbenchAction aboutAction; + + /** The open preferences action. */ private IWorkbenchAction openPreferencesAction; + + /** The save as action. */ private IWorkbenchAction saveAsAction; + + /** The backward history action. */ private IWorkbenchAction backwardHistoryAction; + + /** The forward history action. */ private IWorkbenchAction forwardHistoryAction; + /** The undo action. */ // generic retarget actions private IWorkbenchAction undoAction; + + /** The redo action. */ private IWorkbenchAction redoAction; + + /** The quit action. */ private IWorkbenchAction quitAction; + /** The open workspace action. */ // IDE-specific actions private IWorkbenchAction openWorkspaceAction; + + /** The project property dialog action. */ private IWorkbenchAction projectPropertyDialogAction; + /** The new wizard menu. */ private BaseNewWizardMenu newWizardMenu; + /** The status line item. */ // @issue class is workbench internal private StatusLineContributionItem statusLineItem; @@ -67,13 +113,15 @@ public class GamaActionBarAdvisor extends ActionBarAdvisor { * Indicates if the action builder has been disposed */ private boolean isDisposed = false; + + /** The icons. */ final IIconProvider icons; /** - * Constructs a new action builder which contributes actions - * to the given window. + * Constructs a new action builder which contributes actions to the given window. * - * @param configurer the action bar configurer for the window + * @param configurer + * the action bar configurer for the window */ public GamaActionBarAdvisor(final IActionBarConfigurer configurer) { super(configurer); @@ -84,9 +132,7 @@ public GamaActionBarAdvisor(final IActionBarConfigurer configurer) { /** * Returns the window to which this action builder is contributing. */ - private IWorkbenchWindow getWindow() { - return window; - } + private IWorkbenchWindow getWindow() { return window; } /** * Fills the menu bar with the workbench actions. @@ -116,7 +162,7 @@ private MenuManager createFileMenu() { this.newWizardMenu = new BaseNewWizardMenu(getWindow(), null) { @Override - protected void addItems(final List list) { + protected void addItems(final List list) { addShortcuts(list); } }; @@ -226,10 +272,9 @@ private MenuManager createHelpMenu() { } /** - * Adds a GroupMarker or Separator to a menu. - * The test for whether a separator should be added is done by checking for - * the existence of a preference matching the string - * useSeparator.MENUID.GROUPID that is set to true. + * Adds a GroupMarker or Separator to a menu. The test for whether a separator should be + * added is done by checking for the existence of a preference matching the string useSeparator.MENUID.GROUPID that + * is set to true. * * @param menu * the menu to add to @@ -239,7 +284,7 @@ private MenuManager createHelpMenu() { private void addSeparatorOrGroupMarker(final MenuManager menu, final String groupId) { final String prefId = "useSeparator." + menu.getId() + "." + groupId; //$NON-NLS-1$ //$NON-NLS-2$ final boolean addExtraSeparators = IDEWorkbenchPlugin.getDefault().getPreferenceStore().getBoolean(prefId); - if ( addExtraSeparators ) { + if (addExtraSeparators) { menu.add(new Separator(groupId)); } else { menu.add(new GroupMarker(groupId)); @@ -247,12 +292,11 @@ private void addSeparatorOrGroupMarker(final MenuManager menu, final String grou } /** - * Disposes any resources and unhooks any listeners that are no longer needed. - * Called when the window is closed. + * Disposes any resources and unhooks any listeners that are no longer needed. Called when the window is closed. */ @Override public void dispose() { - if ( isDisposed ) { return; } + if (isDisposed) return; isDisposed = true; getActionBarConfigurer().getStatusLineManager().remove(statusLineItem); @@ -273,7 +317,7 @@ public void dispose() { quitAction = null; openWorkspaceAction = null; projectPropertyDialogAction = null; - if ( newWizardMenu != null ) { + if (newWizardMenu != null) { newWizardMenu.dispose(); newWizardMenu = null; } @@ -282,14 +326,12 @@ public void dispose() { } /** - * Returns true if the menu with the given ID should - * be considered as an OLE container menu. Container menus - * are preserved in OLE menu merging. + * Returns true if the menu with the given ID should be considered as an OLE container menu. Container menus are + * preserved in OLE menu merging. */ @Override public boolean isApplicationMenu(final String menuId) { - if ( menuId.equals(IWorkbenchActionConstants.M_FILE) ) { return true; } - if ( menuId.equals(IWorkbenchActionConstants.M_WINDOW) ) { return true; } + if (IWorkbenchActionConstants.M_FILE.equals(menuId) || IWorkbenchActionConstants.M_WINDOW.equals(menuId)) return true; return false; } @@ -327,33 +369,64 @@ protected void makeActions(final IWorkbenchWindow aWindow) { register(hideShowEditorAction); } + /** + * Creates the property dialog action. + * + * @param aWindow the a window + */ public void createPropertyDialogAction(final IWorkbenchWindow aWindow) { projectPropertyDialogAction = IDEActionFactory.OPEN_PROJECT_PROPERTIES.create(aWindow); register(projectPropertyDialogAction); } + /** + * Creates the open workspace action. + * + * @param aWindow the a window + */ public void createOpenWorkspaceAction(final IWorkbenchWindow aWindow) { openWorkspaceAction = IDEActionFactory.OPEN_WORKSPACE.create(aWindow); register(openWorkspaceAction); } + /** + * Creates the quit action. + * + * @param aWindow the a window + */ public void createQuitAction(final IWorkbenchWindow aWindow) { quitAction = ActionFactory.QUIT.create(aWindow); register(quitAction); } + /** + * Creates the backward history action. + * + * @param aWindow the a window + */ public void createBackwardHistoryAction(final IWorkbenchWindow aWindow) { backwardHistoryAction = ActionFactory.BACKWARD_HISTORY.create(aWindow); register(backwardHistoryAction); } + /** + * Creates the forward history action. + * + * @param aWindow the a window + */ public void createForwardHistoryAction(final IWorkbenchWindow aWindow) { forwardHistoryAction = ActionFactory.FORWARD_HISTORY.create(aWindow); register(forwardHistoryAction); } + /** + * The Class OpenPreferencesAction. + */ private class OpenPreferencesAction extends Action implements IWorkbenchAction { + /** + * Instantiates a new open preferences action. + */ OpenPreferencesAction() { super(WorkbenchMessages.OpenPreferences_text); setId("preferences"); @@ -373,19 +446,35 @@ public void dispose() {} } + /** + * Creates the open preferences action. + * + * @param aWindow the a window + */ public void createOpenPreferencesAction(final IWorkbenchWindow aWindow) { openPreferencesAction = new OpenPreferencesAction(); register(openPreferencesAction); } + /** + * Creates the about action. + * + * @param aWindow the a window + */ public void createAboutAction(final IWorkbenchWindow aWindow) { aboutAction = ActionFactory.ABOUT.create(aWindow); aboutAction.setImageDescriptor(icons.desc("menu.about2")); register(aboutAction); } + /** + * The Class HelpContentsAction. + */ private class HelpContentsAction extends Action implements IWorkbenchAction { + /** + * Instantiates a new help contents action. + */ HelpContentsAction() { setActionDefinitionId(IWorkbenchCommandConstants.HELP_HELP_CONTENTS); setId("helpContents"); @@ -405,41 +494,81 @@ public void dispose() {} } + /** + * Creates the help contents action. + * + * @param aWindow the a window + */ public void createHelpContentsAction(final IWorkbenchWindow aWindow) { helpContentsAction = new HelpContentsAction(); register(helpContentsAction); } + /** + * Creates the close all action. + * + * @param aWindow the a window + */ public void createCloseAllAction(final IWorkbenchWindow aWindow) { closeAllAction = ActionFactory.CLOSE_ALL.create(aWindow); register(closeAllAction); } + /** + * Creates the close action. + * + * @param aWindow the a window + */ public void createCloseAction(final IWorkbenchWindow aWindow) { closeAction = ActionFactory.CLOSE.create(aWindow); register(closeAction); } + /** + * Creates the redo action. + * + * @param aWindow the a window + */ public void createRedoAction(final IWorkbenchWindow aWindow) { redoAction = ActionFactory.REDO.create(aWindow); register(redoAction); } + /** + * Creates the save action. + * + * @param aWindow the a window + */ public void createSaveAction(final IWorkbenchWindow aWindow) { saveAction = ActionFactory.SAVE.create(aWindow); register(saveAction); } + /** + * Creates the save as action. + * + * @param aWindow the a window + */ public void createSaveAsAction(final IWorkbenchWindow aWindow) { saveAsAction = ActionFactory.SAVE_AS.create(aWindow); register(saveAsAction); } + /** + * Creates the save all action. + * + * @param aWindow the a window + */ public void createSaveAllAction(final IWorkbenchWindow aWindow) { saveAllAction = ActionFactory.SAVE_ALL.create(aWindow); register(saveAllAction); } + /** + * Creates the undo action. + * + * @param aWindow the a window + */ public void createUndoAction(final IWorkbenchWindow aWindow) { undoAction = ActionFactory.UNDO.create(aWindow); register(undoAction); @@ -459,45 +588,78 @@ private void makeFeatureDependentActions(final IWorkbenchWindow aWindow) { final String prevState = prefs.getString(stateKey); final String currentState = String.valueOf(Platform.getStateStamp()); final boolean sameState = currentState.equals(prevState); - if ( !sameState ) { - prefs.putValue(stateKey, currentState); - } + if (!sameState) { prefs.putValue(stateKey, currentState); } } + /** + * Gets the cut item. + * + * @return the cut item + */ private IContributionItem getCutItem() { return getItem(ActionFactory.CUT.getId(), ActionFactory.CUT.getCommandId(), "menu.cut2", null, - WorkbenchMessages.Workbench_cut, WorkbenchMessages.Workbench_cutToolTip, null); + WorkbenchMessages.Workbench_cut, WorkbenchMessages.Workbench_cutToolTip, null); } + /** + * Gets the copy item. + * + * @return the copy item + */ private IContributionItem getCopyItem() { return getItem(ActionFactory.COPY.getId(), ActionFactory.COPY.getCommandId(), "menu.copy2", null, - WorkbenchMessages.Workbench_copy, WorkbenchMessages.Workbench_copyToolTip, null); + WorkbenchMessages.Workbench_copy, WorkbenchMessages.Workbench_copyToolTip, null); } + /** + * Gets the paste item. + * + * @return the paste item + */ private IContributionItem getPasteItem() { return getItem(ActionFactory.PASTE.getId(), ActionFactory.PASTE.getCommandId(), "menu.paste2", null, - WorkbenchMessages.Workbench_paste, WorkbenchMessages.Workbench_pasteToolTip, null); + WorkbenchMessages.Workbench_paste, WorkbenchMessages.Workbench_pasteToolTip, null); } + /** + * Gets the prints the item. + * + * @return the prints the item + */ private IContributionItem getPrintItem() { return getItem(ActionFactory.PRINT.getId(), ActionFactory.PRINT.getCommandId(), "menu.print2", null, - WorkbenchMessages.Workbench_print, WorkbenchMessages.Workbench_printToolTip, null); + WorkbenchMessages.Workbench_print, WorkbenchMessages.Workbench_printToolTip, null); } + /** + * Gets the select all item. + * + * @return the select all item + */ private IContributionItem getSelectAllItem() { return getItem(ActionFactory.SELECT_ALL.getId(), ActionFactory.SELECT_ALL.getCommandId(), "action.selectall2", - null, WorkbenchMessages.Workbench_selectAll, WorkbenchMessages.Workbench_selectAllToolTip, null); + null, WorkbenchMessages.Workbench_selectAll, WorkbenchMessages.Workbench_selectAllToolTip, null); } + /** + * Gets the find item. + * + * @return the find item + */ private IContributionItem getFindItem() { return getItem(ActionFactory.FIND.getId(), ActionFactory.FIND.getCommandId(), null, null, - WorkbenchMessages.Workbench_findReplace, WorkbenchMessages.Workbench_findReplaceToolTip, null); + WorkbenchMessages.Workbench_findReplace, WorkbenchMessages.Workbench_findReplaceToolTip, null); } + /** + * Gets the delete item. + * + * @return the delete item + */ private IContributionItem getDeleteItem() { return getItem(ActionFactory.DELETE.getId(), ActionFactory.DELETE.getCommandId(), "menu.delete2", null, - WorkbenchMessages.Workbench_delete, WorkbenchMessages.Workbench_deleteToolTip, - IWorkbenchHelpContextIds.DELETE_RETARGET_ACTION); + WorkbenchMessages.Workbench_delete, WorkbenchMessages.Workbench_deleteToolTip, + IWorkbenchHelpContextIds.DELETE_RETARGET_ACTION); } // private IContributionItem getRevertItem() { @@ -505,36 +667,68 @@ private IContributionItem getDeleteItem() { // WorkbenchMessages.Workbench_revert, WorkbenchMessages.Workbench_revertToolTip, null); // } + /** + * Gets the refresh item. + * + * @return the refresh item + */ private IContributionItem getRefreshItem() { return getItem(ActionFactory.REFRESH.getId(), ActionFactory.REFRESH.getCommandId(), - "navigator/navigator.refresh2", null, WorkbenchMessages.Workbench_refresh, - WorkbenchMessages.Workbench_refreshToolTip, null); + "navigator/navigator.refresh2", null, WorkbenchMessages.Workbench_refresh, + WorkbenchMessages.Workbench_refreshToolTip, null); } + /** + * Gets the properties item. + * + * @return the properties item + */ private IContributionItem getPropertiesItem() { return getItem(ActionFactory.PROPERTIES.getId(), ActionFactory.PROPERTIES.getCommandId(), "display.sidebar2", - null, WorkbenchMessages.Workbench_properties, WorkbenchMessages.Workbench_propertiesToolTip, null); + null, WorkbenchMessages.Workbench_properties, WorkbenchMessages.Workbench_propertiesToolTip, null); } + /** + * Gets the move item. + * + * @return the move item + */ private IContributionItem getMoveItem() { return getItem(ActionFactory.MOVE.getId(), ActionFactory.MOVE.getCommandId(), "navigator/navigator.move2", null, - WorkbenchMessages.Workbench_move, WorkbenchMessages.Workbench_moveToolTip, null); + WorkbenchMessages.Workbench_move, WorkbenchMessages.Workbench_moveToolTip, null); } + /** + * Gets the rename item. + * + * @return the rename item + */ private IContributionItem getRenameItem() { return getItem(ActionFactory.RENAME.getId(), ActionFactory.RENAME.getCommandId(), "navigator/navigator.rename2", - null, WorkbenchMessages.Workbench_rename, WorkbenchMessages.Workbench_renameToolTip, null); + null, WorkbenchMessages.Workbench_rename, WorkbenchMessages.Workbench_renameToolTip, null); } + /** + * Gets the item. + * + * @param actionId the action id + * @param commandId the command id + * @param image the image + * @param disabledImage the disabled image + * @param label the label + * @param tooltip the tooltip + * @param helpContextId the help context id + * @return the item + */ private IContributionItem getItem(final String actionId, final String commandId, final String image, - final String disabledImage, final String label, final String tooltip, final String helpContextId) { + final String disabledImage, final String label, final String tooltip, final String helpContextId) { final IActionCommandMappingService acms = getWindow().getService(IActionCommandMappingService.class); acms.map(actionId, commandId); final CommandContributionItemParameter commandParm = new CommandContributionItemParameter(getWindow(), actionId, - commandId, null, image != null ? icons.desc(image) : null, null, null, label, null, tooltip, - CommandContributionItem.STYLE_PUSH, null, false); + commandId, null, image != null ? icons.desc(image) : null, null, null, label, null, tooltip, + CommandContributionItem.STYLE_PUSH, null, false); return new CommandContributionItem(commandParm); } } diff --git a/msi.gama.application/src/msi/gama/application/workbench/PerspectiveHelper.java b/msi.gama.application/src/msi/gama/application/workbench/PerspectiveHelper.java index a91d13ac3c..507ef8edc2 100644 --- a/msi.gama.application/src/msi/gama/application/workbench/PerspectiveHelper.java +++ b/msi.gama.application/src/msi/gama/application/workbench/PerspectiveHelper.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * PerspectiveHelper.java, in msi.gama.application, is part of the source code of the GAMA modeling and simulation - * platform (v.1.8.2). + * PerspectiveHelper.java, in msi.gama.application, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.application.workbench; @@ -64,7 +64,7 @@ public class PerspectiveHelper { public static String currentPerspectiveId = PERSPECTIVE_MODELING_ID; /** The current simulation perspective. */ - public static IPerspectiveDescriptor currentSimulationPerspective = null; + public static volatile IPerspectiveDescriptor currentSimulationPerspective = null; /** The active editor. */ public static IEditorInput activeEditor; diff --git a/msi.gama.application/src/msi/gama/application/workbench/ThemeHelper.java b/msi.gama.application/src/msi/gama/application/workbench/ThemeHelper.java index 5e39f4024b..d62bf77af7 100644 --- a/msi.gama.application/src/msi/gama/application/workbench/ThemeHelper.java +++ b/msi.gama.application/src/msi/gama/application/workbench/ThemeHelper.java @@ -3,7 +3,7 @@ * ThemeHelper.java, in msi.gama.application, is part of the source code of the GAMA modeling and simulation platform * (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -83,7 +83,7 @@ public class ThemeHelper { private static final List listeners = new ArrayList<>(); /** The engine. */ - private static IThemeEngine engine; + private static volatile IThemeEngine engine; /** The bundle. */ private static Bundle bundle = Platform.getBundle("msi.gama.application"); @@ -288,8 +288,8 @@ public static IThemeEngine getEngine() { */ private static ThemeEngine getThemeEngine() { BundleContext context = bundle.getBundleContext(); - ServiceReference ref = context.getServiceReference(IThemeManager.class.getName()); - IThemeManager manager = (IThemeManager) context.getService(ref); + ServiceReference ref = context.getServiceReference(IThemeManager.class); + IThemeManager manager = context.getService(ref); return (ThemeEngine) manager.getEngineForDisplay(PlatformUI.getWorkbench().getActiveWorkbenchWindow() == null ? Display.getCurrent() : PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getDisplay()); } diff --git a/msi.gama.application/src/msi/gama/application/workspace/WorkspaceModelsManager.java b/msi.gama.application/src/msi/gama/application/workspace/WorkspaceModelsManager.java index 02c729a916..8c37ef9293 100644 --- a/msi.gama.application/src/msi/gama/application/workspace/WorkspaceModelsManager.java +++ b/msi.gama.application/src/msi/gama/application/workspace/WorkspaceModelsManager.java @@ -3,7 +3,7 @@ * WorkspaceModelsManager.java, in msi.gama.application, is part of the source code of the GAMA modeling and simulation * platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -17,6 +17,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; @@ -296,7 +297,7 @@ protected void execute(final IProgressMonitor monitor) * */ - public static String UNCLASSIFIED_MODELS = "Unclassified Models"; + public static final String UNCLASSIFIED_MODELS = "Unclassified Models"; /** * Creates the unclassified models project. @@ -441,9 +442,9 @@ public void loadModelsLibrary() { } // If the directory is not empty, we should maybe try to recreate the projects (if they do not exist...) - try { - for (java.nio.file.Path r : Files.newDirectoryStream(java.nio.file.Path.of(workspaceLocation), - Files::isDirectory)) { + try (DirectoryStream paths = + Files.newDirectoryStream(java.nio.file.Path.of(workspaceLocation), Files::isDirectory)) { + for (java.nio.file.Path r : paths) { File folder = r.toFile(); if (isGamaProject(folder)) { createOrUpdateProject(folder.getName()); } } diff --git a/msi.gama.core/src/msi/gama/common/geometry/GeometryUtils.java b/msi.gama.core/src/msi/gama/common/geometry/GeometryUtils.java index cd48433cdf..8249067d57 100644 --- a/msi.gama.core/src/msi/gama/common/geometry/GeometryUtils.java +++ b/msi.gama.core/src/msi/gama/common/geometry/GeometryUtils.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.common.geometry.GeometryUtils.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling - * and simulation platform (v. 1.8.1) + * GeometryUtils.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -86,20 +86,41 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GeometryUtils { + /** The envelope computers. */ private static List envelopeComputers = new ArrayList<>(); + /** + * Adds the envelope computer. + * + * @param ec + * the ec + */ public static void addEnvelopeComputer(final IEnvelopeComputer ec) { envelopeComputers.add(ec); } + /** The Constant GEOMETRY_FACTORY. */ public final static GamaGeometryFactory GEOMETRY_FACTORY = new GamaGeometryFactory(); + + /** The Constant PREPARED_GEOMETRY_FACTORY. */ public final static PreparedGeometryFactory PREPARED_GEOMETRY_FACTORY = new PreparedGeometryFactory(); + /** + * Distance on polyline. + * + * @param line + * the line + * @param pt1 + * the pt 1 + * @param pt2 + * the pt 2 + * @return the double + */ public static Double distanceOnPolyline(final IShape line, final GamaPoint pt1, final GamaPoint pt2) { int indexS = 0; int indexT = 0; - IList points = (IList) line.getPoints(); + IList points = line.getPoints(); int nbSp = points.size(); if (nbSp == 2) return pt1.euclidianDistanceTo(pt2); @@ -148,6 +169,15 @@ public static Double distanceOnPolyline(final IShape line, final GamaPoint pt1, return distance; } + /** + * Point in geom. + * + * @param geom + * the geom + * @param rand + * the rand + * @return the gama point + */ public static GamaPoint pointInGeom(final Geometry geom, final RandomUtils rand) { // WARNING Only in 2D for Polygons ! if (geom == null || geom.getCoordinate() == null) return null; @@ -215,11 +245,10 @@ public static GamaPoint pointInGeom(final Geometry geom, final RandomUtils rand) } final int index = Random.opRndChoice(GAMA.getRuntimeScope(), distribution); return pointInGeom(geom.getGeometryN(index), rand); - } else if (geom instanceof MultiPolygon) { + } + if (geom instanceof MultiPolygon) { final IList distribution = GamaListFactory.create(Types.FLOAT); - for (int i = 0; i < geom.getNumGeometries(); i++) { - distribution.add(geom.getGeometryN(i).getArea()); - } + for (int i = 0; i < geom.getNumGeometries(); i++) { distribution.add(geom.getGeometryN(i).getArea()); } final int index = Random.opRndChoice(GAMA.getRuntimeScope(), distribution); return pointInGeom(geom.getGeometryN(index), rand); } @@ -230,11 +259,27 @@ public static GamaPoint pointInGeom(final Geometry geom, final RandomUtils rand) } + /** + * Point in geom. + * + * @param shape + * the shape + * @param rand + * the rand + * @return the gama point + */ public static GamaPoint pointInGeom(final IShape shape, final RandomUtils rand) { if (shape == null) return null; return pointInGeom(shape.getInnerGeometry(), rand); } + /** + * Minimise length. + * + * @param coords + * the coords + * @return the coordinate[] + */ private static Coordinate[] minimiseLength(final Coordinate[] coords) { final double dist1 = GEOMETRY_FACTORY.createLineString(coords).getLength(); final Coordinate[] coordstest1 = new Coordinate[3]; @@ -255,16 +300,32 @@ private static Coordinate[] minimiseLength(final Coordinate[] coords) { return coords; } + /** + * Nb common points. + * + * @param p1 + * the p 1 + * @param p2 + * the p 2 + * @return the int + */ public static int nbCommonPoints(final Geometry p1, final Geometry p2) { try (final ICollector cp = Collector.getSet()) { final List coords = Arrays.asList(p1.getCoordinates()); - for (final Coordinate pt : p2.getCoordinates()) { - if (coords.contains(pt)) { cp.add(pt); } - } + for (final Coordinate pt : p2.getCoordinates()) { if (coords.contains(pt)) { cp.add(pt); } } return cp.size(); } } + /** + * Extract points. + * + * @param triangle + * the triangle + * @param connectedNodes + * the connected nodes + * @return the coordinate[] + */ public static Coordinate[] extractPoints(final IShape triangle, final Set connectedNodes) { final Coordinate[] coords = triangle.getInnerGeometry().getCoordinates(); final int degree = connectedNodes.size(); @@ -280,26 +341,33 @@ public static Coordinate[] extractPoints(final IShape triangle, final Set hexagonalGridFromGeom(final IShape geom, final int nbRows, final int nbColumns) { final Envelope env = geom.getEnvelope(); final double widthEnv = env.getWidth(); @@ -348,6 +427,19 @@ public static IList hexagonalGridFromGeom(final IShape geom, final int n return geoms; } + /** + * Square discretization. + * + * @param geom + * the geom + * @param nb_squares + * the nb squares + * @param overlaps + * the overlaps + * @param coeff_precision + * the coeff precision + * @return the i list + */ public static IList squareDiscretization(final Geometry geom, final int nb_squares, final boolean overlaps, final double coeff_precision) { double size = Math.sqrt(geom.getArea() / nb_squares); @@ -375,19 +467,45 @@ public static IList squareDiscretization(final Geometry geom, final int if (nb - nb_squares > rectToRemove.size()) { squares.removeAll(rectToRemove); } else { - for (int i = 0; i < nb - nb_squares; i++) { - squares.remove(rectToRemove.get(i)); - } + for (int i = 0; i < nb - nb_squares; i++) { squares.remove(rectToRemove.get(i)); } } } return squares; } + /** + * Discretization. + * + * @param geom + * the geom + * @param size_x + * the size x + * @param size_y + * the size y + * @param overlaps + * the overlaps + * @return the i list + */ public static IList discretization(final Geometry geom, final double size_x, final double size_y, final boolean overlaps) { return discretization(geom, size_x, size_y, overlaps, null); } + /** + * Discretization. + * + * @param geom + * the geom + * @param size_x + * the size x + * @param size_y + * the size y + * @param overlaps + * the overlaps + * @param borders + * the borders + * @return the i list + */ public static IList discretization(final Geometry geom, final double size_x, final double size_y, final boolean overlaps, final List borders) { final IList geoms = GamaListFactory.create(Types.GEOMETRY); @@ -435,6 +553,17 @@ public static IList discretization(final Geometry geom, final double siz return geoms; } + /** + * Geometry decomposition. + * + * @param geom + * the geom + * @param x_size + * the x size + * @param y_size + * the y size + * @return the i list + */ public static IList geometryDecomposition(final IShape geom, final double x_size, final double y_size) { final IList geoms = GamaListFactory.create(Types.GEOMETRY); final double zVal = geom.getLocation().getZ(); @@ -454,6 +583,15 @@ public static IList geometryDecomposition(final IShape geom, final doubl return geoms; } + /** + * Voronoi. + * + * @param scope + * the scope + * @param points + * the points + * @return the i list + */ public static IList voronoi(final IScope scope, final IList points) { final IList geoms = GamaListFactory.create(Types.GEOMETRY); final VoronoiDiagramBuilder dtb = new VoronoiDiagramBuilder(); @@ -468,6 +606,17 @@ public static IList voronoi(final IScope scope, final IList p return geoms; } + /** + * Voronoi. + * + * @param scope + * the scope + * @param points + * the points + * @param clip + * the clip + * @return the i list + */ public static IList voronoi(final IScope scope, final IList points, final IShape clip) { final IList geoms = GamaListFactory.create(Types.GEOMETRY); final VoronoiDiagramBuilder dtb = new VoronoiDiagramBuilder(); @@ -482,6 +631,15 @@ public static IList voronoi(final IScope scope, final IList p return geoms; } + /** + * Triangulation. + * + * @param scope + * the scope + * @param lines + * the lines + * @return the i list + */ public static IList triangulation(final IScope scope, final IList lines) { final IList geoms = GamaListFactory.create(Types.GEOMETRY); final ConformingDelaunayTriangulationBuilder dtb = new ConformingDelaunayTriangulationBuilder(); @@ -498,6 +656,21 @@ public static IList triangulation(final IScope scope, final IList triangulation(final IScope scope, final Geometry geom, final double toleranceTriangulation, final double toleranceClip, final boolean approxClipping) { final IList geoms = GamaListFactory.create(Types.GEOMETRY); @@ -527,6 +700,19 @@ public static IList triangulation(final IScope scope, final Geometry geo return geoms; } + /** + * Filter geoms. + * + * @param geom + * the geom + * @param clip + * the clip + * @param sizeTol + * the size tol + * @param approxClipping + * the approx clipping + * @return the i list + */ private static IList filterGeoms(final GeometryCollection geom, final Geometry clip, final double sizeTol, final boolean approxClipping) { if (geom == null) return null; @@ -568,6 +754,14 @@ private static IList filterGeoms(final GeometryCollection geom, final Ge return result; } + /** + * Iterate over triangles. + * + * @param polygon + * the polygon + * @param action + * the action + */ public static void iterateOverTriangles(final Polygon polygon, final Consumer action) { final double elevation = getContourCoordinates(polygon).averageZ(); final double sizeTol = Math.sqrt(polygon.getArea()) / 100.0; @@ -595,6 +789,21 @@ public static void iterateOverTriangles(final Polygon polygon, final Consumer squeletisation(final IScope scope, final Geometry geom, final double toleranceTriangulation, final double toleranceClip, final boolean approxClipping) { final List network = new ArrayList<>(); @@ -606,19 +815,26 @@ public static List squeletisation(final IScope scope, final Geometry if (cc.size() > 2) { for (final Object o : cc) { final GamaShape node = (GamaShape) o; - final Coordinate[] coordsArr = - GeometryUtils.extractPoints(node, new LinkedHashSet(Graphs.neighborsOf(scope, graph, node))); + final Coordinate[] coordsArr = GeometryUtils.extractPoints(node, + new LinkedHashSet(Graphs.neighborsOf(scope, graph, node))); if (coordsArr != null) { network.add(GEOMETRY_FACTORY.createLineString(coordsArr)); } } } else if (cc.size() == 2) { final Coordinate[] coordsArr = GeometryUtils.extractPoints((GamaShape) cc.get(0), (GamaShape) cc.get(1)); - if (coordsArr != null) { network.add(GEOMETRY_FACTORY.createLineString(coordsArr)); } + network.add(GEOMETRY_FACTORY.createLineString(coordsArr)); } } return network; } + /** + * Builds the geometry JTS. + * + * @param geomG + * the geom G + * @return the geometry + */ public static Geometry buildGeometryJTS(final List>> geomG) { final IShape.Type geometryType = geometryType(geomG); switch (geometryType) { @@ -633,60 +849,76 @@ public static Geometry buildGeometryJTS(final List>> geomG) case MULTIPOINT: final int nb = geomG.size(); final Point[] geoms = new Point[nb]; - for (int i = 0; i < nb; i++) { - geoms[i] = (Point) buildPoint(geomG.get(i)); - } + for (int i = 0; i < nb; i++) { geoms[i] = (Point) buildPoint(geomG.get(i)); } return GEOMETRY_FACTORY.createMultiPoint(geoms); case MULTILINESTRING: final int n = geomG.size(); final LineString[] lines = new LineString[n]; - for (int i = 0; i < n; i++) { - lines[i] = (LineString) buildLine(geomG.get(i)); - } + for (int i = 0; i < n; i++) { lines[i] = (LineString) buildLine(geomG.get(i)); } return GEOMETRY_FACTORY.createMultiLineString(lines); case MULTIPOLYGON: final int n3 = geomG.size(); final Polygon[] polys = new Polygon[n3]; - for (int i = 0; i < n3; i++) { - polys[i] = (Polygon) buildPolygon(geomG.get(i)); - } + for (int i = 0; i < n3; i++) { polys[i] = (Polygon) buildPolygon(geomG.get(i)); } return GEOMETRY_FACTORY.createMultiPolygon(polys); default: return null; } } + /** + * Builds the point. + * + * @param listPoints + * the list points + * @return the geometry + */ private static Geometry buildPoint(final List> listPoints) { return GEOMETRY_FACTORY.createPoint(listPoints.get(0).get(0)); } + /** + * Builds the geometry collection. + * + * @param geoms + * the geoms + * @return the geometry + */ public static Geometry buildGeometryCollection(final List geoms) { final int nb = geoms.size(); final Geometry[] geometries = new Geometry[nb]; - for (int i = 0; i < nb; i++) { - geometries[i] = geoms.get(i).getInnerGeometry(); - } + for (int i = 0; i < nb; i++) { geometries[i] = geoms.get(i).getInnerGeometry(); } return GEOMETRY_FACTORY.createGeometryCollection(geometries); } + /** + * Builds the line. + * + * @param listPoints + * the list points + * @return the geometry + */ private static Geometry buildLine(final List> listPoints) { final List coords = listPoints.get(0); final int nb = coords.size(); final Coordinate[] coordinates = new Coordinate[nb]; - for (int i = 0; i < nb; i++) { - coordinates[i] = coords.get(i); - } + for (int i = 0; i < nb; i++) { coordinates[i] = coords.get(i); } return GEOMETRY_FACTORY.createLineString(coordinates); } + /** + * Builds the polygon. + * + * @param listPoints + * the list points + * @return the geometry + */ private static Geometry buildPolygon(final List> listPoints) { final List coords = listPoints.get(0); final int nb = coords.size(); final Coordinate[] coordinates = new Coordinate[nb]; - for (int i = 0; i < nb; i++) { - coordinates[i] = coords.get(i); - } + for (int i = 0; i < nb; i++) { coordinates[i] = coords.get(i); } final int nbHoles = listPoints.size() - 1; LinearRing[] holes = null; if (nbHoles > 0) { @@ -695,15 +927,20 @@ private static Geometry buildPolygon(final List> listPoints) { final List coordsH = listPoints.get(i + 1); final int nbp = coordsH.size(); final Coordinate[] coordinatesH = new Coordinate[nbp]; - for (int j = 0; j < nbp; j++) { - coordinatesH[j] = coordsH.get(j); - } + for (int j = 0; j < nbp; j++) { coordinatesH[j] = coordsH.get(j); } holes[i] = GEOMETRY_FACTORY.createLinearRing(coordinatesH); } } return GEOMETRY_FACTORY.createPolygon(GEOMETRY_FACTORY.createLinearRing(coordinates), holes); } + /** + * Geometry type. + * + * @param listPoints + * the list points + * @return the i shape. type + */ private static IShape.Type geometryType(final List>> listPoints) { final int size = listPoints.size(); if (size == 0) return NULL; @@ -721,6 +958,13 @@ private static IShape.Type geometryType(final List>> listPo } } + /** + * Geometry type simp. + * + * @param listPoints + * the list points + * @return the i shape. type + */ private static IShape.Type geometryTypeSimp(final List> listPoints) { if (listPoints.isEmpty() || listPoints.get(0).isEmpty()) return NULL; final List list0 = listPoints.get(0); @@ -730,6 +974,15 @@ private static IShape.Type geometryTypeSimp(final List> listPoin return POLYGON; } + /** + * Locs on geometry. + * + * @param geom + * the geom + * @param distance + * the distance + * @return the i list + */ public static IList locsOnGeometry(final Geometry geom, final Double distance) { final IList locs = GamaListFactory.create(Types.POINT); if (geom instanceof Point) { @@ -745,17 +998,7 @@ public static IList locsOnGeometry(final Geometry geom, final Double final Coordinate t = coordsSimp[i + 1]; while (true) { final double dist = s.distance3D(t); - if (distance - distCur < dist) { - final double distTravel = distance - distCur; - final double ratio = distTravel / dist; - final double x_s = s.x + ratio * (t.x - s.x); - final double y_s = s.y + ratio * (t.y - s.y); - final double z_s = s.z + ratio * (t.z - s.z); - s = new Coordinate(x_s, y_s, z_s); - locs.add(new GamaPoint(s)); - distCur = 0; - - } else { + if (distance - distCur >= dist) { if (distance - distCur > dist) { distCur += dist; } else { @@ -764,6 +1007,14 @@ public static IList locsOnGeometry(final Geometry geom, final Double } break; } + final double distTravel = distance - distCur; + final double ratio = distTravel / dist; + final double x_s = s.x + ratio * (t.x - s.x); + final double y_s = s.y + ratio * (t.y - s.y); + final double z_s = s.z + ratio * (t.z - s.z); + s = new Coordinate(x_s, y_s, z_s); + locs.add(new GamaPoint(s)); + distCur = 0; } } @@ -780,13 +1031,20 @@ public static IList locsOnGeometry(final Geometry geom, final Double return locs; } + /** + * Locs along geometry. + * + * @param geom + * the geom + * @param rates + * the rates + * @return the i list + */ public static IList locsAlongGeometry(final Geometry geom, final List rates) { final IList locs = GamaListFactory.create(Types.POINT); if (rates == null || rates.isEmpty()) return locs; if (geom instanceof Point) { - for (int i = 0; i < rates.size(); i++) { - locs.add(new GamaPoint(geom.getCoordinate())); - } + for (int i = 0; i < rates.size(); i++) { locs.add(new GamaPoint(geom.getCoordinate())); } } else if (geom instanceof LineString) { for (Double rate : rates) { final Coordinate[] coordsSimp = geom.getCoordinates(); @@ -817,12 +1075,12 @@ public static IList locsAlongGeometry(final Geometry geom, final List s = new Coordinate(x_s, y_s, z_s); locs.add(new GamaPoint(s)); break; - } else if (distance - distCur > dist) { - distCur += dist; - } else { + } + if (distance - distCur <= dist) { locs.add(new GamaPoint(t)); break; } + distCur += dist; } } } else if (geom instanceof Polygon) { @@ -837,11 +1095,19 @@ public static IList locsAlongGeometry(final Geometry geom, final List // Created date:24-Feb-2013: Process for SQL - MAP type // Modified: 03-Jan-2014 + /** + * Compute envelope from. + * + * @param scope + * the scope + * @param obj + * the obj + * @return the envelope 3 D + */ public static Envelope3D computeEnvelopeFrom(final IScope scope, final Object obj) { Envelope3D result = null; - if (obj instanceof ISpecies) - return computeEnvelopeFrom(scope, ((ISpecies) obj).getPopulation(scope)); - else if (obj instanceof Number) { + if (obj instanceof ISpecies) return computeEnvelopeFrom(scope, ((ISpecies) obj).getPopulation(scope)); + if (obj instanceof Number) { final double size = ((Number) obj).doubleValue(); result = Envelope3D.of(0, size, 0, size, 0, size); } else if (obj instanceof GamaPoint) { @@ -873,6 +1139,15 @@ else if (obj instanceof Number) { return result; } + /** + * Split at. + * + * @param g + * the g + * @param pt + * the pt + * @return the i list + */ private static IList split_at(final Geometry g, final GamaPoint pt) { final IList lines = GamaListFactory.create(Types.GEOMETRY); // final GamaPoint p = new GamaPoint(pt); @@ -888,16 +1163,12 @@ private static IList split_at(final Geometry g, final GamaPoint pt) { } } final GamaPoint[] coords1 = new GamaPoint[indexTarget + 2]; - for (int i = 0; i <= indexTarget; i++) { - coords1[i] = coords[i]; - } + for (int i = 0; i <= indexTarget; i++) { coords1[i] = coords[i]; } coords1[indexTarget + 1] = pt; lines.add(new GamaShape(GEOMETRY_FACTORY.createLineString(coords1, false))); final GamaPoint[] coords2 = new GamaPoint[coords.length - indexTarget]; coords2[0] = pt; - for (int i = indexTarget + 1, k = 1; i < coords.length; i++, k++) { - coords2[k] = coords[i]; - } + for (int i = indexTarget + 1, k = 1; i < coords.length; i++, k++) { coords2[k] = coords[i]; } lines.add(new GamaShape(GEOMETRY_FACTORY.createLineString(coords2, false))); } else if (g instanceof MultiLineString) { final Point point = GEOMETRY_FACTORY.createPoint(pt); @@ -917,6 +1188,15 @@ private static IList split_at(final Geometry g, final GamaPoint pt) { } + /** + * Split at. + * + * @param geom + * the geom + * @param pt + * the pt + * @return the i list + */ public static IList split_at(final IShape geom, final GamaPoint pt) { return split_at(geom.getInnerGeometry(), pt); } @@ -940,6 +1220,13 @@ public static IShape smooth(final Geometry geom, final double fit) { return new GamaShape(JTS.smooth(geom, fit, GEOMETRY_FACTORY)); } + /** + * Gets the contour coordinates. + * + * @param g + * the g + * @return the contour coordinates + */ public static ICoordinates getContourCoordinates(final Polygon g) { if (g.isEmpty()) return ICoordinates.EMPTY; if (g.getExteriorRing().getCoordinateSequence() instanceof CoordinateArraySequence) @@ -947,16 +1234,37 @@ public static ICoordinates getContourCoordinates(final Polygon g) { return (ICoordinates) g.getExteriorRing().getCoordinateSequence(); } + /** + * Gets the contour coordinates. + * + * @param g + * the g + * @return the contour coordinates + */ public static ICoordinates getContourCoordinates(final LineString g) { if (g.isEmpty()) return ICoordinates.EMPTY; return (ICoordinates) g.getCoordinateSequence(); } + /** + * Gets the contour coordinates. + * + * @param g + * the g + * @return the contour coordinates + */ public static ICoordinates getContourCoordinates(final Point g) { if (g.isEmpty()) return ICoordinates.EMPTY; return (ICoordinates) g.getCoordinateSequence(); } + /** + * Gets the contour coordinates. + * + * @param g + * the g + * @return the contour coordinates + */ public static ICoordinates getContourCoordinates(final Geometry g) { if (g instanceof Polygon) return getContourCoordinates((Polygon) g); if (g instanceof LineString) return getContourCoordinates((LineString) g); @@ -965,21 +1273,49 @@ public static ICoordinates getContourCoordinates(final Geometry g) { return ICoordinates.EMPTY; } + /** + * Gets the points of. + * + * @param shape + * the shape + * @return the points of + */ public static GamaPoint[] getPointsOf(final IShape shape) { final Geometry g = shape.getInnerGeometry(); return getContourCoordinates(g).toCoordinateArray(); } + /** + * Gets the points of. + * + * @param g + * the g + * @return the points of + */ public static GamaPoint[] getPointsOf(final Geometry g) { return getContourCoordinates(g).toCoordinateArray(); } + /** + * Gets the first point of. + * + * @param shape + * the shape + * @return the first point of + */ public static GamaPoint getFirstPointOf(final IShape shape) { final Geometry g = shape.getInnerGeometry(); if (g.isEmpty()) return null; return (GamaPoint) g.getCoordinates()[0]; } + /** + * Gets the last point of. + * + * @param shape + * the shape + * @return the last point of + */ public static GamaPoint getLastPointOf(final IShape shape) { final Geometry g = shape.getInnerGeometry(); if (g.isEmpty()) return null; @@ -1002,14 +1338,28 @@ public static void applyToInnerGeometries(final Geometry g, final GeometryFilter } else if (g instanceof GeometryCollection) { applyToInnerGeometries((GeometryCollection) g, f); } } + /** + * Apply to inner geometries. + * + * @param g + * the g + * @param f + * the f + */ public static void applyToInnerGeometries(final Polygon g, final GeometryFilter f) { final int holes = g.getNumInteriorRing(); if (holes == 0) return; - for (int i = 0; i < holes; i++) { - g.getInteriorRingN(i).apply(f); - } + for (int i = 0; i < holes; i++) { g.getInteriorRingN(i).apply(f); } } + /** + * Apply to inner geometries. + * + * @param g + * the g + * @param f + * the f + */ public static void applyToInnerGeometries(final GeometryCollection g, final GeometryFilter f) { final int geoms = g.getNumGeometries(); if (geoms == 0) return; @@ -1019,6 +1369,16 @@ public static void applyToInnerGeometries(final GeometryCollection g, final Geom } } + /** + * Translate. + * + * @param geometry + * the geometry + * @param previous + * the previous + * @param location + * the location + */ public static void translate(final Geometry geometry, final GamaPoint previous, final GamaPoint location) { final double dx = location.x - previous.x; final double dy = location.y - previous.y; @@ -1026,6 +1386,18 @@ public static void translate(final Geometry geometry, final GamaPoint previous, translate(geometry, dx, dy, dz); } + /** + * Translate. + * + * @param geometry + * the geometry + * @param dx + * the dx + * @param dy + * the dy + * @param dz + * the dz + */ public static void translate(final Geometry geometry, final double dx, final double dy, final double dz) { geometry.apply((final Coordinate p) -> { p.x += dx; @@ -1035,6 +1407,16 @@ public static void translate(final Geometry geometry, final double dx, final dou geometry.geometryChanged(); } + /** + * Rotate. + * + * @param geometry + * the geometry + * @param center + * the center + * @param rotation + * the rotation + */ public static void rotate(final Geometry geometry, final GamaPoint center, final AxisAngle rotation) { if (rotation == null) return; final Rotation3D r = new Rotation3D.CenteredOn(rotation, center); @@ -1042,14 +1424,35 @@ public static void rotate(final Geometry geometry, final GamaPoint center, final geometry.geometryChanged(); } + /** + * Gets the y negated coordinates. + * + * @param geom + * the geom + * @return the y negated coordinates + */ public static ICoordinates getYNegatedCoordinates(final Geometry geom) { return getContourCoordinates(geom).yNegated(); } + /** + * Gets the holes number. + * + * @param p + * the p + * @return the holes number + */ public static int getHolesNumber(final Geometry p) { return p instanceof Polygon ? ((Polygon) p).getNumInteriorRing() : 0; } + /** + * Geometry collection management. + * + * @param gjts + * the gjts + * @return the geometry + */ public static Geometry geometryCollectionManagement(final Geometry gjts) { if (!(gjts instanceof GeometryCollection) || gjts instanceof MultiPoint || gjts instanceof MultiLineString || gjts instanceof MultiPolygon) @@ -1073,43 +1476,42 @@ public static Geometry geometryCollectionManagement(final Geometry gjts) { if (list.size() == 1) return list.get(0); if (dimMax == 0) { Point[] pts = new Point[list.size()]; - for (int i = 0; i < pts.length; i++) { - pts[i] = (Point) list.get(i); - } + for (int i = 0; i < pts.length; i++) { pts[i] = (Point) list.get(i); } return GEOMETRY_FACTORY.createMultiPoint(pts); - } else if (dimMax == 1) { + } + if (dimMax == 1) { LineString[] ls = new LineString[list.size()]; - for (int i = 0; i < ls.length; i++) { - ls[i] = (LineString) list.get(i); - } + for (int i = 0; i < ls.length; i++) { ls[i] = (LineString) list.get(i); } return GEOMETRY_FACTORY.createMultiLineString(ls); - } else { - Polygon[] ps = new Polygon[list.size()]; - for (int i = 0; i < ps.length; i++) { - ps[i] = (Polygon) list.get(i); - } - return GEOMETRY_FACTORY.createMultiPolygon(ps); } + Polygon[] ps = new Polygon[list.size()]; + for (int i = 0; i < ps.length; i++) { ps[i] = (Polygon) list.get(i); } + return GEOMETRY_FACTORY.createMultiPolygon(ps); } return gc; } + /** + * Clean geometry. + * + * @param g + * the g + * @return the geometry + */ public static Geometry cleanGeometry(final Geometry g) { // follow the proposition of https://locationtech.github.io/jts/jts-faq.html#G1 if (g == null || g.isEmpty()) return g; Geometry g2 = g.buffer(0.0, BufferParameters.DEFAULT_QUADRANT_SEGMENTS, BufferParameters.CAP_FLAT); if (g2.isEmpty()) { - if (g instanceof Polygon) { - Polygon p = (Polygon) g; - Geometry g3 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getExteriorRing().getCoordinates()); - for (int i = 0; i < p.getNumInteriorRing(); i++) { - Geometry g4 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getInteriorRingN(i).getCoordinates()); - g3 = g3.difference(g4); - } - return g3; - } else - return GeometryUtils.GEOMETRY_FACTORY.createGeometry(g); + if (!(g instanceof Polygon)) return GeometryUtils.GEOMETRY_FACTORY.createGeometry(g); + Polygon p = (Polygon) g; + Geometry g3 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getExteriorRing().getCoordinates()); + for (int i = 0; i < p.getNumInteriorRing(); i++) { + Geometry g4 = GeometryUtils.GEOMETRY_FACTORY.createPolygon(p.getInteriorRingN(i).getCoordinates()); + g3 = g3.difference(g4); + } + return g3; } return g2; } diff --git a/msi.gama.core/src/msi/gama/common/preferences/GamaPreferenceStore.java b/msi.gama.core/src/msi/gama/common/preferences/GamaPreferenceStore.java index ddc53c6106..4f18e80935 100644 --- a/msi.gama.core/src/msi/gama/common/preferences/GamaPreferenceStore.java +++ b/msi.gama.core/src/msi/gama/common/preferences/GamaPreferenceStore.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * GamaPreferenceStore.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform - * (v.1.8.2). + * GamaPreferenceStore.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.common.preferences; @@ -63,7 +63,7 @@ public abstract class GamaPreferenceStore { } /** The store. */ - private static GamaPreferenceStore STORE; + private static volatile GamaPreferenceStore STORE; /** The Constant NODE_NAME. */ private static final String NODE_NAME = "gama"; diff --git a/msi.gama.core/src/msi/gama/common/preferences/Pref.java b/msi.gama.core/src/msi/gama/common/preferences/Pref.java index 1ae0ee1972..0a5a0fe901 100644 --- a/msi.gama.core/src/msi/gama/common/preferences/Pref.java +++ b/msi.gama.core/src/msi/gama/common/preferences/Pref.java @@ -2,7 +2,7 @@ * * Pref.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -24,6 +24,7 @@ import msi.gama.util.GamaMapFactory; import msi.gaml.types.IType; import msi.gaml.types.Types; +import ummisco.gama.dev.utils.COUNTER; /** * The Class Pref. @@ -51,10 +52,7 @@ public interface ValueProvider { } /** The order. */ - static int ORDER = 0; - - /** The order. */ - private final int order = ORDER++; + private final int order = COUNTER.GET(); /** The in gaml. */ private final boolean inGaml; diff --git a/msi.gama.core/src/msi/gama/common/util/FileUtils.java b/msi.gama.core/src/msi/gama/common/util/FileUtils.java index 7f154ba0b2..596f2deb19 100644 --- a/msi.gama.core/src/msi/gama/common/util/FileUtils.java +++ b/msi.gama.core/src/msi/gama/common/util/FileUtils.java @@ -1,9 +1,8 @@ /******************************************************************************************************* * - * msi.gama.common.util.FileUtils.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * FileUtils.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -58,25 +57,46 @@ @SuppressWarnings ("deprecation") public class FileUtils { - public static ThreadLocal WEB = ThreadLocal.withInitial(() -> Webb.create()); + /** The web. */ + public static ThreadLocal WEB = ThreadLocal.withInitial(Webb::create); + + /** The Constant URL_SEPARATOR_REPLACEMENT. */ public static final String URL_SEPARATOR_REPLACEMENT = "+_+"; + + /** The Constant COPY_OF. */ public static final String COPY_OF = "copy of "; + + /** The Constant HOME. */ public static final String HOME = "~"; + + /** The Constant SEPARATOR. */ public static final String SEPARATOR = "/"; + + /** The Constant CACHE_FOLDER_PATH. */ public static final IPath CACHE_FOLDER_PATH = new Path(".cache"); + + /** The Constant EXTERNAL_FOLDER_PATH. */ public static final IPath EXTERNAL_FOLDER_PATH = new Path("external"); + + /** The root. */ static IWorkspaceRoot ROOT = ResourcesPlugin.getWorkspace().getRoot(); + + /** The file system. */ static IFileSystem FILE_SYSTEM = EFS.getLocalFileSystem(); + + /** The user home. */ static String USER_HOME = System.getProperty("user.home"); + + /** The Constant WORKSPACE_URI. */ static final URI WORKSPACE_URI = URI.createURI(ROOT.getLocationURI().toString(), false); + + /** The Constant CACHE. */ public static final File CACHE; static { DEBUG.OFF(); CACHE = new File(ROOT.getLocation().toFile().getAbsolutePath() + SEPARATOR + CACHE_FOLDER_PATH.toString()); - if (!CACHE.exists()) { - CACHE.mkdirs(); - } + if (!CACHE.exists()) { CACHE.mkdirs(); } try { ROOT.getPathVariableManager().setValue("CACHE_LOC", ROOT.getLocation().append(CACHE_FOLDER_PATH)); } catch (final CoreException e) { @@ -100,6 +120,17 @@ static boolean isAbsolutePath(final String filePath) { // Add a thin layer of workspace-based searching in order to resolve linked // resources. + /** + * Construct absolute file path. + * + * @param scope + * the scope + * @param filePath + * the file path + * @param mustExist + * the must exist + * @return the string + */ // Should be able to catch most of the calls to relative resources as well static public String constructAbsoluteFilePath(final IScope scope, final String filePath, final boolean mustExist) { String fp; @@ -112,20 +143,16 @@ static public String constructAbsoluteFilePath(final IScope scope, final String URI modelBase = null; if (scope != null) { final IModel m = scope.getModel(); - if (m != null) { - modelBase = m.getURI(); - } + if (m != null) { modelBase = m.getURI(); } } final String file = findOutsideWorkspace(fp, modelBase, mustExist); - if (file != null) { - // DEBUG.OUT("Hit with EFS-based search: " + file); + if (file != null) // DEBUG.OUT("Hit with EFS-based search: " + file); return file; - } } if (scope != null) { final IExperimentAgent a = scope.getExperiment(); // No need to search more if the experiment is null - if (a == null) { return fp; } + if (a == null) return fp; if (!a.isHeadless()) { // Necessary to ask the workspace for the containers as projects might be linked final List paths = a.getWorkingPaths().stream() @@ -144,6 +171,17 @@ static public String constructAbsoluteFilePath(final IScope scope, final String return OldFileUtils.constructAbsoluteFilePathAlternate(scope, fp, mustExist); } + /** + * Find in workspace. + * + * @param fp + * the fp + * @param container + * the container + * @param mustExist + * the must exist + * @return the string + */ private static String findInWorkspace(final String fp, final IContainer container, final boolean mustExist) { final IPath full = container.getFullPath().append(fp); IResource file = ROOT.getFile(full); @@ -151,53 +189,66 @@ private static String findInWorkspace(final String fp, final IContainer containe // Might be a folder we're looking for file = ROOT.getFolder(full); } - if (!file.exists()) { - if (mustExist) { return null; } - } + if (!file.exists() && mustExist) return null; final IPath loc = file.getLocation(); // cf. #2997 - if (loc == null) { return fp; } + if (loc == null) return fp; return loc.toString(); // getLocation() works for regular and linked files } + /** + * Find outside workspace. + * + * @param fp + * the fp + * @param modelBase + * the model base + * @param mustExist + * the must exist + * @return the string + */ private static String findOutsideWorkspace(final String fp, final URI modelBase, final boolean mustExist) { - if (!mustExist) { return fp; } + if (!mustExist) return fp; final IFileStore file = FILE_SYSTEM.getStore(new Path(fp)); final IFileInfo info = file.fetchInfo(); if (info.exists()) { final IFile linkedFile = createLinkToExternalFile(fp, modelBase); - if (linkedFile == null) { return fp; } + if (linkedFile == null) return fp; return linkedFile.getLocation().toFile().getAbsolutePath(); } return null; } + /** + * Creates the link to external file. + * + * @param path + * the path + * @param workspaceResource + * the workspace resource + * @return the i file + */ public static IFile createLinkToExternalFile(final String path, final URI workspaceResource) { // Always try to return the full file, without creating a link, if the file // happens to be in the workspace // (manageable by it) final IPath filePath = new Path(path); - final IResource[] resources = ROOT.findFilesForLocation(filePath); - if (resources.length > 0) { - final IResource r = resources[0]; - if (r instanceof IFile) { return (IFile) r; } - } + final IFile[] resources = ROOT.findFilesForLocation(filePath); + if (resources.length > 0) return resources[0]; final IFolder folder = createExternalFolder(workspaceResource); - if (folder == null) { return null; } + if (folder == null) return null; // We try to find an existing file linking to this uri (in case it has been // renamed, for instance) IFile file = findExistingLinkedFile(folder, path); - if (file != null) { return file; } + if (file != null) return file; // We get the file with the same last name // If it already exists, we need to find it a new name as it doesnt point to the // same absolute file String fileName = new Path(path).lastSegment(); final int i = fileName.lastIndexOf(URL_SEPARATOR_REPLACEMENT); - if (i > -1) { - fileName = fileName.substring(i + URL_SEPARATOR_REPLACEMENT.length()); - } + if (i > -1) { fileName = fileName.substring(i + URL_SEPARATOR_REPLACEMENT.length()); } file = correctlyNamedFile(folder, fileName); return createLinkedFile(path, file); } @@ -214,46 +265,57 @@ public static IFile createLinkToExternalFile(final String path, final URI worksp * @return an URI or null if it cannot be determined. */ public static URI getURI(final String target, final URI existingResource) { - if (target == null) { return null; } + if (target == null) return null; try { final IPath path = Path.fromOSString(target); final IFileStore file = EFS.getLocalFileSystem().getStore(path); final IFileInfo info = file.fetchInfo(); - if (info.exists()) { - // We have an absolute file - final URI fileURI = URI.createFileURI(target); - return fileURI; + if (info.exists()) return URI.createFileURI(target); + final URI first = URI.createURI(target, false); + URI root; + if (!existingResource.isPlatformResource()) { + root = URI.createPlatformResourceURI(existingResource.toString(), false); } else { - final URI first = URI.createURI(target, false); - URI root; - if (!existingResource.isPlatformResource()) { - root = URI.createPlatformResourceURI(existingResource.toString(), false); - } else { - root = existingResource; - } - if (root == null) { - root = WORKSPACE_URI; - } - final URI iu = first.resolve(root); - if (isFileExistingInWorkspace(iu)) { return iu; } - return null; + root = existingResource; } + if (root == null) { root = WORKSPACE_URI; } + final URI iu = first.resolve(root); + if (isFileExistingInWorkspace(iu)) return iu; + return null; } catch (final Exception e) { return null; } } + /** + * Checks if is file existing in workspace. + * + * @param uri + * the uri + * @return true, if is file existing in workspace + */ public static boolean isFileExistingInWorkspace(final URI uri) { - if (uri == null) { return false; } + if (uri == null) return false; final IFile file = getWorkspaceFile(uri); - if (file != null) { return file.exists(); } + if (file != null) return file.exists(); return false; } + /** + * Gets the file. + * + * @param path + * the path + * @param root + * the root + * @param mustExist + * the must exist + * @return the file + */ public static IFile getFile(final String path, final URI root, final boolean mustExist) { final URI uri = getURI(path, root); if (uri != null) { - if (uri.isPlatformResource()) { return getWorkspaceFile(uri); } + if (uri.isPlatformResource()) return getWorkspaceFile(uri); return createLinkToExternalFile(path, root); } return null; @@ -266,6 +328,15 @@ public static IFile getFile(final String path, final URI root, final boolean mus // return linkAndGetExternalFile(URI.decode(path), workspaceResource); // } + /** + * Creates the linked file. + * + * @param path + * the path + * @param file + * the file + * @return the i file + */ private static IFile createLinkedFile(final String path, final IFile file) { java.net.URI resolvedURI = null; final java.net.URI javaURI = URIUtil.toURI(path);// new java.io.File(path).toURI(); @@ -284,6 +355,15 @@ private static IFile createLinkedFile(final String path, final IFile file) { return file; } + /** + * Correctly named file. + * + * @param folder + * the folder + * @param fileName + * the file name + * @return the i file + */ private static IFile correctlyNamedFile(final IFolder folder, final String fileName) { IFile file; String fn = fileName; @@ -294,6 +374,15 @@ private static IFile correctlyNamedFile(final IFolder folder, final String fileN return file; } + /** + * Find existing linked file. + * + * @param folder + * the folder + * @param name + * the name + * @return the i file + */ private static IFile findExistingLinkedFile(final IFolder folder, final String name) { final IFile[] result = new IFile[1]; try { @@ -311,15 +400,21 @@ private static IFile findExistingLinkedFile(final IFolder folder, final String n } catch (final CoreException e1) { e1.printStackTrace(); } - final IFile file = result[0]; - return file; + return result[0]; } + /** + * Creates the external folder. + * + * @param workspaceResource + * the workspace resource + * @return the i folder + */ private static IFolder createExternalFolder(final URI workspaceResource) { - if (workspaceResource == null || !isFileExistingInWorkspace(workspaceResource)) { return null; } + if (workspaceResource == null || !isFileExistingInWorkspace(workspaceResource)) return null; final IFile root = getWorkspaceFile(workspaceResource); final IProject project = root.getProject(); - if (!project.exists()) { return null; } + if (!project.exists()) return null; final IFolder folder = project.getFolder(EXTERNAL_FOLDER_PATH); if (!folder.exists()) { try { @@ -332,6 +427,13 @@ private static IFolder createExternalFolder(final URI workspaceResource) { return folder; } + /** + * Gets the workspace file. + * + * @param uri + * the uri + * @return the workspace file + */ public static IFile getWorkspaceFile(final URI uri) { final IPath uriAsPath = new Path(URI.decode(uri.toString())); IFile file; @@ -340,31 +442,52 @@ public static IFile getWorkspaceFile(final URI uri) { } catch (final Exception e1) { return null; } - if (file != null && file.exists()) { return file; } + if (file != null && file.exists()) return file; final String uriAsText = uri.toPlatformString(true); final IPath path = uriAsText != null ? new Path(uriAsText) : null; - if (path == null) { return null; } + if (path == null) return null; try { file = ROOT.getFile(path); } catch (final Exception e) { return null; } - if (file != null && file.exists()) { return file; } + if (file != null && file.exists()) return file; return null; } + /** + * Construct absolute temp file path. + * + * @param scope + * the scope + * @param url + * the url + * @return the string + */ public static String constructAbsoluteTempFilePath(final IScope scope, final URL url) { return CACHE.getAbsolutePath() + SEPARATOR + url.getHost() + URL_SEPARATOR_REPLACEMENT + url.getPath().replace(SEPARATOR, URL_SEPARATOR_REPLACEMENT); } + /** + * Construct relative temp file path. + * + * @param scope + * the scope + * @param url + * the url + * @return the string + */ private static String constructRelativeTempFilePath(final IScope scope, final URL url) { return "" + CacheLocationProvider.NAME + "" + SEPARATOR + url.getHost() + URL_SEPARATOR_REPLACEMENT + url.getPath().replace(SEPARATOR, URL_SEPARATOR_REPLACEMENT); } + /** + * Clean cache. + */ public static void cleanCache() { if (GamaPreferences.External.CORE_HTTP_EMPTY_CACHE.getValue()) { final File[] files = CACHE.listFiles(); @@ -382,13 +505,29 @@ public static void cleanCache() { } } + /** + * Checks if is directory or null external file. + * + * @param path + * the path + * @return true, if is directory or null external file + */ public static boolean isDirectoryOrNullExternalFile(final String path) { final IFileStore external = FILE_SYSTEM.getStore(new Path(path)); final IFileInfo info = external.fetchInfo(); - if (info.isDirectory() || !info.exists()) { return true; } + if (info.isDirectory() || !info.exists()) return true; return false; } + /** + * Fetch to temp file. + * + * @param scope + * the scope + * @param url + * the url + * @return the string + */ @SuppressWarnings ("deprecation") public static String fetchToTempFile(final IScope scope, final URL url) { String pathName = constructRelativeTempFilePath(scope, url); @@ -405,9 +544,7 @@ public static String fetchToTempFile(final IScope scope, final URL url) { pathName = ROOT.getPathVariableManager().resolvePath(new Path(pathName)).toOSString(); // pathName = ROOT.getPathVariableManager().resolveURI(uri).getPath(); final java.nio.file.Path p = new File(pathName).toPath(); - if (Files.exists(p)) { - Files.delete(p); - } + if (Files.exists(p)) { Files.delete(p); } Files.copy(in, p); } } catch (final IOException | WebbException e) { diff --git a/msi.gama.core/src/msi/gama/common/util/GISUtils.java b/msi.gama.core/src/msi/gama/common/util/GISUtils.java index fe08e8d358..ad3f79b697 100644 --- a/msi.gama.core/src/msi/gama/common/util/GISUtils.java +++ b/msi.gama.core/src/msi/gama/common/util/GISUtils.java @@ -1,9 +1,8 @@ /******************************************************************************************************* * - * msi.gama.common.util.GISUtils.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * GISUtils.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -11,16 +10,29 @@ package msi.gama.common.util; import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import org.geotools.referencing.CRS; +import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; +/** + * The Class GISUtils. + */ public class GISUtils { + /** + * Manage google CRS. + * + * @param url + * the url + * @return the coordinate reference system + */ // ugly method to manage Google CRS.... hoping that it is better managed by the next versions of Geotools public static CoordinateReferenceSystem manageGoogleCRS(final URL url) { CoordinateReferenceSystem crs = null; @@ -34,7 +46,7 @@ public static CoordinateReferenceSystem manageGoogleCRS(final URL url) { crs = CRS.decode("EPSG:3857"); } } - } catch (final Exception e) {} + } catch (final IOException | URISyntaxException | FactoryException e) {} return crs; } } diff --git a/msi.gama.core/src/msi/gama/common/util/JavaUtils.java b/msi.gama.core/src/msi/gama/common/util/JavaUtils.java index cb5b3c13b9..3fc54f40ac 100644 --- a/msi.gama.core/src/msi/gama/common/util/JavaUtils.java +++ b/msi.gama.core/src/msi/gama/common/util/JavaUtils.java @@ -1,9 +1,8 @@ /******************************************************************************************************* * - * msi.gama.common.util.JavaUtils.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * JavaUtils.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -39,18 +38,53 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class JavaUtils { + /** The null iterator. */ + static Iterator NULL_ITERATOR = new UnmodifiableIterator<>() { + + @Override + public boolean hasNext() { + return false; + } + + @Override + public Object next() { + return null; + } + }; + + /** The Constant IMPLEMENTATION_CLASSES. */ public final static Map> IMPLEMENTATION_CLASSES = new HashMap(); + + /** The interfaces. */ private static Multimap INTERFACES = HashMultimap. create(); + + /** The superclasses. */ private static Multimap SUPERCLASSES = HashMultimap. create(); + /** + * Key of. + * + * @param base + * the base + * @param others + * the others + * @return the int + */ private static int keyOf(final Class base, final Iterable> others) { int result = base.hashCode(); - for (final Class other : others) { - result += other.hashCode(); - } + for (final Class other : others) { result += other.hashCode(); } return result; } + /** + * All interfaces of. + * + * @param c + * the c + * @param in + * the in + * @return the sets the + */ private static final Set allInterfacesOf(final Class c, final Set in) { if (c == null) return Collections.EMPTY_SET; if (!INTERFACES.containsKey(c)) { @@ -66,6 +100,15 @@ private static final Set allInterfacesOf(final Class c, final Set return (Set) INTERFACES.get(c); } + /** + * All superclasses of. + * + * @param c + * the c + * @param in + * the in + * @return the sets the + */ private static final Set allSuperclassesOf(final Class c, final Set in) { if (c == null) return null; if (!SUPERCLASSES.containsKey(c)) { @@ -78,6 +121,17 @@ private static final Set allSuperclassesOf(final Class c, final Set) SUPERCLASSES.get(c); } + /** + * Collect implementation classes. + * + * @param baseClass + * the base class + * @param skillClasses + * the skill classes + * @param in + * the in + * @return the list + */ public static List collectImplementationClasses(final Class baseClass, final Iterable> skillClasses, final Set in) { final int key = keyOf(baseClass, skillClasses); @@ -92,7 +146,7 @@ public static List collectImplementationClasses(final Class baseClass, if (o1.isAssignableFrom(o2)) return -1; if (o2.isAssignableFrom(o1)) return 1; if (o1.isInterface() && !o2.isInterface()) return -1; - if (o2.isInterface() && !o1.isInterface()) return 1; + if (o2.isInterface() && !o1.isInterface()) {} return 1; }); @@ -102,20 +156,18 @@ public static List collectImplementationClasses(final Class baseClass, } + /** + * Iterator. + * + * @param + * the generic type + * @param array + * the array + * @return the iterator + */ public static Iterator iterator(final Object[] array) { - if (array != null) return (Iterator) Iterators.forArray(array); - return new UnmodifiableIterator<>() { - - @Override - public boolean hasNext() { - return false; - } - - @Override - public F next() { - return null; - } - }; + if (array != null && array.length > 0) return (Iterator) Iterators.forArray(array); + return NULL_ITERATOR; } } diff --git a/msi.gama.core/src/msi/gama/common/util/PoolUtils.java b/msi.gama.core/src/msi/gama/common/util/PoolUtils.java index e387f954b0..2b41ca3998 100644 --- a/msi.gama.core/src/msi/gama/common/util/PoolUtils.java +++ b/msi.gama.core/src/msi/gama/common/util/PoolUtils.java @@ -1,3 +1,13 @@ +/******************************************************************************************************* + * + * PoolUtils.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.common.util; import java.util.LinkedHashSet; @@ -10,9 +20,15 @@ import msi.gama.common.preferences.GamaPreferences; import ummisco.gama.dev.utils.DEBUG; +/** + * The Class PoolUtils. + */ public class PoolUtils { + /** The pools. */ static Set POOLS = new LinkedHashSet<>(); + + /** The pool. */ static public boolean POOL = GamaPreferences.External.USE_POOLING.getValue(); static { DEBUG.OFF(); @@ -22,6 +38,9 @@ public class PoolUtils { }); } + /** + * Write stats. + */ public static void WriteStats() { if (!DEBUG.IS_ON()) return; DEBUG.SECTION("Pool statistics"); @@ -32,29 +51,81 @@ public static void WriteStats() { }); } - public interface ObjectFactory { - T createNew(); - } + /** + * A factory for creating Object objects. + * + * @param the generic type + */ + public interface ObjectFactory { /** + * Creates a new Object object. + * + * @return the t + */ + T createNew(); } + /** + * The Interface ObjectCopy. + * + * @param the generic type + */ public interface ObjectCopy { + /** + * Creates the new. + * + * @param copyFrom the copy from + * @param copyTo the copy to + */ void createNew(T copyFrom, T copyTo); } - public interface ObjectCleaner { - void clean(T object); - } + /** + * The Interface ObjectCleaner. + * + * @param the generic type + */ + public interface ObjectCleaner { /** + * Clean. + * + * @param object the object + */ + void clean(T object); } + /** + * The Class ObjectPool. + * + * @param the generic type + */ public static class ObjectPool implements IDisposable { + /** The name. */ private String name; + + /** The created. */ private long accessed, released, created; + + /** The factory. */ private final ObjectFactory factory; + + /** The copy. */ private final ObjectCopy copy; + + /** The cleaner. */ private final ObjectCleaner cleaner; + + /** The objects. */ private final Queue objects; + + /** The active. */ public boolean active; + /** + * Instantiates a new object pool. + * + * @param factory the factory + * @param copy the copy + * @param cleaner the cleaner + */ private ObjectPool(final ObjectFactory factory, final ObjectCopy copy, final ObjectCleaner cleaner) { this.factory = factory; this.copy = copy; @@ -62,6 +133,11 @@ private ObjectPool(final ObjectFactory factory, final ObjectCopy copy, fin objects = Queues.synchronizedDeque(Queues.newArrayDeque()); } + /** + * Gets the. + * + * @return the t + */ public T get() { if (!POOL || !active) return factory.createNew(); accessed++; @@ -74,13 +150,24 @@ public T get() { return result; } + /** + * Gets the. + * + * @param from the from + * @return the t + */ public T get(final T from) { T result = get(); if (copy != null) { copy.createNew(from, result); } return result; } - public void release(final T... tt) { + /** + * Release. + * + * @param tt the tt + */ + public void release(@SuppressWarnings ("unchecked") final T... tt) { if (tt == null) return; for (T t : tt) { if (cleaner != null) { cleaner.clean(t); } diff --git a/msi.gama.core/src/msi/gama/kernel/batch/exploration/ExplicitExploration.java b/msi.gama.core/src/msi/gama/kernel/batch/exploration/ExplicitExploration.java index 7ab33ae0d4..d642e72fbd 100644 --- a/msi.gama.core/src/msi/gama/kernel/batch/exploration/ExplicitExploration.java +++ b/msi.gama.core/src/msi/gama/kernel/batch/exploration/ExplicitExploration.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.kernel.batch.HillClimbing.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * ExplicitExploration.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.batch.exploration; @@ -34,6 +34,9 @@ import msi.gaml.operators.Cast; import msi.gaml.types.IType; +/** + * The Class ExplicitExploration. + */ @symbol ( name = IKeyword.EXPLICIT, kind = ISymbolKind.BATCH_METHOD, @@ -53,8 +56,7 @@ type = IType.LIST, of = IType.MAP, optional = false, - doc = @doc ("the list of parameter sets to explore; a parameter set is defined by a map: key: name of the variable, value: expression for the value of the variable")) - }, + doc = @doc ("the list of parameter sets to explore; a parameter set is defined by a map: key: name of the variable, value: expression for the value of the variable")) }, omissible = IKeyword.NAME) @doc ( value = "This algorithm run simulations with the given parameter sets", @@ -70,12 +72,24 @@ isExecutable = false) }) }) public class ExplicitExploration extends AExplorationAlgorithm { + /** The Constant PARAMETER_SET. */ protected static final String PARAMETER_SET = "parameter_sets"; - protected List> parameterSets; - public ExplicitExploration(final IDescription desc) { super(desc); } - @Override public void setChildren(Iterable children) { } - + /** The parameter sets. */ + protected List> parameterSets; + + /** + * Instantiates a new explicit exploration. + * + * @param desc the desc + */ + public ExplicitExploration(final IDescription desc) { + super(desc); + } + + @Override + public void setChildren(final Iterable children) {} + @Override public void explore(final IScope scope) throws GamaRuntimeException { List solutions = buildParameterSets(scope, new ArrayList<>(), 0); @@ -86,16 +100,16 @@ public void explore(final IScope scope) throws GamaRuntimeException { } } - @SuppressWarnings("unchecked") + @SuppressWarnings ("unchecked") @Override - public List buildParameterSets(IScope scope, List sets, int index) { + public List buildParameterSets(final IScope scope, final List sets, final int index) { IExpression psexp = getFacet(PARAMETER_SET); - parameterSets = (List>) Cast.asList(scope, psexp.value(scope)); - for (Map parameterSet : parameterSets) { + parameterSets = Cast.asList(scope, psexp.value(scope)); + for (Map parameterSet : parameterSets) { ParametersSet p = new ParametersSet(); for (String v : parameterSet.keySet()) { Object val = parameterSet.get(v); - p.put(v,(val instanceof IExpression) ? ((IExpression) val).value(scope) : val); + p.put(v, val instanceof IExpression ? ((IExpression) val).value(scope) : val); } sets.add(p); } diff --git a/msi.gama.core/src/msi/gama/kernel/batch/optimization/Swarm.java b/msi.gama.core/src/msi/gama/kernel/batch/optimization/Swarm.java index abc2017171..504b3cd64d 100644 --- a/msi.gama.core/src/msi/gama/kernel/batch/optimization/Swarm.java +++ b/msi.gama.core/src/msi/gama/kernel/batch/optimization/Swarm.java @@ -1,3 +1,13 @@ +/******************************************************************************************************* + * + * Swarm.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.kernel.batch.optimization; import java.util.ArrayList; @@ -5,6 +15,7 @@ import java.util.Hashtable; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.stream.Collectors; import msi.gama.common.interfaces.IKeyword; @@ -29,6 +40,9 @@ import msi.gaml.operators.Cast; import msi.gaml.types.IType; +/** + * The Class Swarm. + */ @symbol ( name = IKeyword.PSO, kind = ISymbolKind.BATCH_METHOD, @@ -99,29 +113,58 @@ isExecutable = false) }) }) public class Swarm extends AOptimizationAlgorithm { - public static final double DEFAULT_INERTIA = 0.729844; - public static final double DEFAULT_COGNITIVE = 1.496180; // Cognitive component. - public static final double DEFAULT_SOCIAL = 1.496180; // Social component. + /** The Constant DEFAULT_INERTIA. */ + public static final double DEFAULT_INERTIA = 0.729844; + + /** The Constant DEFAULT_COGNITIVE. */ + public static final double DEFAULT_COGNITIVE = 1.496180; // Cognitive component. + + /** The Constant DEFAULT_SOCIAL. */ + public static final double DEFAULT_SOCIAL = 1.496180; // Social component. - protected static final String ITER_MAX = "iter_max"; + /** The Constant ITER_MAX. */ + protected static final String ITER_MAX = "iter_max"; + + /** The Constant NUM_PARTICLES. */ protected static final String NUM_PARTICLES = "num_particles"; + + /** The Constant INERTIA_WEIGHT. */ protected static final String INERTIA_WEIGHT = "weight_inertia"; + + /** The Constant COGNITIVE_WEIGHT. */ protected static final String COGNITIVE_WEIGHT = "weight_cognitive"; - protected static final String SOCIAL_WEIGHT = "weight_social"; + /** The Constant SOCIAL_WEIGHT. */ + protected static final String SOCIAL_WEIGHT = "weight_social"; + + /** The stopping criterion. */ StoppingCriterion stoppingCriterion = null; + + /** The max it. */ int maxIt; + + /** The num particles. */ int numParticles; + + /** The weight inertia. */ double weightInertia; + + /** The weight cognitive. */ double weightCognitive; + + /** The weight social. */ double weightSocial; + /** + * Instantiates a new swarm. + * + * @param species the species + */ public Swarm(final IDescription species) { super(species); initParams(); } - @Override public void initParams(final IScope scope) { final IExpression maxItExp = getFacet(ITER_MAX); @@ -129,74 +172,80 @@ public void initParams(final IScope scope) { maxIt = Cast.asInt(scope, maxItExp.value(scope)); stoppingCriterion = new StoppingCriterionMaxIt(maxIt); } - + final IExpression numParticExp = getFacet(NUM_PARTICLES); if (maxItExp != null) { numParticles = Cast.asInt(scope, numParticExp.value(scope)); } else { numParticles = 10; } - + final IExpression intertiaExp = getFacet(INERTIA_WEIGHT); if (intertiaExp != null) { weightInertia = Cast.asFloat(scope, intertiaExp.value(scope)); } else { weightInertia = DEFAULT_INERTIA; } - + final IExpression cognitiveExp = getFacet(COGNITIVE_WEIGHT); if (cognitiveExp != null) { weightCognitive = Cast.asFloat(scope, cognitiveExp.value(scope)); } else { - weightCognitive = DEFAULT_COGNITIVE ; + weightCognitive = DEFAULT_COGNITIVE; } - + final IExpression socialExp = getFacet(SOCIAL_WEIGHT); if (socialExp != null) { weightSocial = Cast.asFloat(scope, socialExp.value(scope)); } else { - weightSocial = DEFAULT_SOCIAL ; + weightSocial = DEFAULT_SOCIAL; } } @Override public ParametersSet findBestSolution(final IScope scope) throws GamaRuntimeException { Particle[] particles = initialize(scope); - + int nbIt = 0; - final Map endingCritParams = new Hashtable<>(); + final Map endingCritParams = new Hashtable<>(); endingCritParams.put("Iteration", Integer.valueOf(nbIt)); while (!stoppingCriterion.stopSearchProcess(endingCritParams)) { - Map> soltTotest = (Map>) GamaMapFactory.create(); - - if (GamaExecutorService.CONCURRENCY_SIMULATIONS_ALL.getValue() && ! currentExperiment.getParametersToExplore().isEmpty()) { - for (Particle particle : particles ) { - List ps = null; - if (soltTotest.containsKey(particle.getPosition())) { - ps = soltTotest.get(particle.getPosition()); - } else { - ps = new ArrayList<>(); - } - ps.add(particle); - soltTotest.put(particle.getPosition(), ps); - } - } - evaluation(particles, soltTotest); - for (Particle p : particles) { - updateVelocity(scope, p); - p.updatePosition(scope); - } - - nbIt++; - endingCritParams.put("Iteration", Integer.valueOf(nbIt)); - } - - + Map> soltTotest = GamaMapFactory.create(); + + if (GamaExecutorService.CONCURRENCY_SIMULATIONS_ALL.getValue() + && !currentExperiment.getParametersToExplore().isEmpty()) { + for (Particle particle : particles) { + List ps = null; + if (soltTotest.containsKey(particle.getPosition())) { + ps = soltTotest.get(particle.getPosition()); + } else { + ps = new ArrayList<>(); + } + ps.add(particle); + soltTotest.put(particle.getPosition(), ps); + } + } + evaluation(particles, soltTotest); + for (Particle p : particles) { + updateVelocity(scope, p); + p.updatePosition(scope); + } + + nbIt++; + endingCritParams.put("Iteration", Integer.valueOf(nbIt)); + } + return getBestSolution(); - } + } - public Map testSolutions(Collection solutions) { + /** + * Test solutions. + * + * @param solutions the solutions + * @return the map + */ + public Map testSolutions(final Collection solutions) { Map results = GamaMapFactory.create(); solutions.removeIf(a -> a == null); List solTotest = new ArrayList<>(); @@ -208,117 +257,145 @@ public Map testSolutions(Collection soluti } } Map res = currentExperiment.launchSimulationsWithSolution(solTotest).entrySet().stream() - .collect(Collectors.toMap( - e -> e.getKey(), - e -> (Double) e.getValue().get(IKeyword.FITNESS).get(0) - )); + .collect(Collectors.toMap(Entry::getKey, e -> (Double) e.getValue().get(IKeyword.FITNESS).get(0))); testedSolutions.putAll(res); results.putAll(res); - + return results; } - - public void evaluation(Particle[] particles, Map> soltTotest ) { - if (GamaExecutorService.CONCURRENCY_SIMULATIONS_ALL.getValue() && ! currentExperiment.getParametersToExplore().isEmpty()) { - Map res = testSolutions(soltTotest.keySet()); - for (ParametersSet ps : res.keySet()) { - for (Particle particle : soltTotest.get(ps)) { - particle.updatePersonalBest(); - //updateGlobalBest(particle); - } - } - - } else { - for (int i = 0; i < numParticles; i++) { - Particle particle = particles[i]; - particle.eval(); - - particle.updatePersonalBest(); - // updateGlobalBest(particle); - } - } - + + /** + * Evaluation. + * + * @param particles the particles + * @param soltTotest the solt totest + */ + public void evaluation(final Particle[] particles, final Map> soltTotest) { + if (GamaExecutorService.CONCURRENCY_SIMULATIONS_ALL.getValue() + && !currentExperiment.getParametersToExplore().isEmpty()) { + Map res = testSolutions(soltTotest.keySet()); + for (ParametersSet ps : res.keySet()) { + for (Particle particle : soltTotest.get(ps)) { + particle.updatePersonalBest(); + // updateGlobalBest(particle); + } + } + + } else { + for (int i = 0; i < numParticles; i++) { + Particle particle = particles[i]; + particle.eval(); + + particle.updatePersonalBest(); + // updateGlobalBest(particle); + } + } + + } + + /** + * Create a set of particles, each with random starting positions. + * + * @return an array of particles + */ + private Particle[] initialize(final IScope scope) { + Particle[] particles = new Particle[numParticles]; + Map> soltTotest = GamaMapFactory.create(); + for (int i = 0; i < numParticles; i++) { + Particle particle = new Particle(scope, currentExperiment, this, testedSolutions); + particles[i] = particle; + if (GamaExecutorService.CONCURRENCY_SIMULATIONS_ALL.getValue() + && !currentExperiment.getParametersToExplore().isEmpty()) { + List ps = null; + if (soltTotest.containsKey(particle.getPosition())) { + ps = soltTotest.get(particle.getPosition()); + } else { + ps = new ArrayList<>(); + } + ps.add(particle); + soltTotest.put(particle.getPosition(), ps); + } + } + evaluation(particles, soltTotest); + + return particles; + } + + /** + * Update the velocity of a particle using the velocity update formula + * + * @param particle + * the particle to update + */ + private void updateVelocity(final IScope scope, final Particle particle) { + ParametersSet oldVelocity = particle.getVelocity(); + ParametersSet pBest = new ParametersSet(particle.getBestPosition()); + ParametersSet gBest = new ParametersSet(bestSolution); + ParametersSet pos = particle.getPosition(); + + double r1 = scope.getRandom().next(); + double r2 = scope.getRandom().next(); + + // The first product of the formula. + ParametersSet newVelocity = new ParametersSet(oldVelocity); + newVelocity = mul(scope, newVelocity, weightInertia); + + // The second product of the formula. + pBest = sub(scope, pBest, pos); + pBest = mul(scope, pBest, weightCognitive); + pBest = mul(scope, pBest, r1); + newVelocity = add(scope, newVelocity, pBest); + + // The third product of the formula. + gBest = sub(scope, gBest, pos); + gBest = mul(scope, gBest, weightSocial); + gBest = mul(scope, gBest, r2); + newVelocity = add(scope, newVelocity, gBest); + + particle.setVelocity(newVelocity); + } + + /** + * Mul. + * + * @param scope the scope + * @param set the set + * @param val the val + * @return the parameters set + */ + protected ParametersSet mul(final IScope scope, final ParametersSet set, final double val) { + for (String key : set.keySet()) { set.put(key, Cast.asFloat(scope, set.get(key)) * val); } + return set; + } + + /** + * Sub. + * + * @param scope the scope + * @param set1 the set 1 + * @param set2 the set 2 + * @return the parameters set + */ + protected ParametersSet sub(final IScope scope, final ParametersSet set1, final ParametersSet set2) { + for (String key : set1.keySet()) { + set1.put(key, Cast.asFloat(scope, set1.get(key)) - Cast.asFloat(scope, set2.get(key))); + } + return set1; + } + + /** + * Adds the. + * + * @param scope the scope + * @param set1 the set 1 + * @param set2 the set 2 + * @return the parameters set + */ + protected ParametersSet add(final IScope scope, final ParametersSet set1, final ParametersSet set2) { + for (String key : set1.keySet()) { + set1.put(key, Cast.asFloat(scope, set1.get(key)) + Cast.asFloat(scope, set2.get(key))); + } + return set1; } - /** - * Create a set of particles, each with random starting positions. - * @return an array of particles - */ - private Particle[] initialize (IScope scope) { - Particle[] particles = new Particle[numParticles]; - Map> soltTotest = (Map>) GamaMapFactory.create(); - for (int i = 0; i < numParticles; i++) { - Particle particle = new Particle(scope, currentExperiment, this, testedSolutions); - particles[i] = particle; - if (GamaExecutorService.CONCURRENCY_SIMULATIONS_ALL.getValue() && ! currentExperiment.getParametersToExplore().isEmpty()) { - List ps = null; - if (soltTotest.containsKey(particle.getPosition())) { - ps = soltTotest.get(particle.getPosition()); - } else { - ps = new ArrayList<>(); - } - ps.add(particle); - soltTotest.put(particle.getPosition(), ps); - } - } - evaluation(particles, soltTotest); - - return particles; - } - - - - /** - * Update the velocity of a particle using the velocity update formula - * @param particle the particle to update - */ - private void updateVelocity (IScope scope, Particle particle) { - ParametersSet oldVelocity = particle.getVelocity(); - ParametersSet pBest = new ParametersSet(particle.getBestPosition()); - ParametersSet gBest = new ParametersSet(bestSolution); - ParametersSet pos = particle.getPosition(); - - double r1 = scope.getRandom().next(); - double r2 = scope.getRandom().next(); - - // The first product of the formula. - ParametersSet newVelocity = new ParametersSet(oldVelocity); - newVelocity = mul(scope, newVelocity, weightInertia); - - // The second product of the formula. - pBest = sub(scope,pBest,pos); - pBest= mul(scope, pBest,weightCognitive); - pBest = mul(scope, pBest, r1); - newVelocity = add(scope, newVelocity, pBest); - - // The third product of the formula. - gBest = sub(scope,gBest,pos); - gBest= mul(scope, gBest,weightSocial); - gBest = mul(scope, gBest, r2); - newVelocity = add(scope, newVelocity,gBest); - - particle.setVelocity(newVelocity); - } - - protected ParametersSet mul(IScope scope, ParametersSet set, double val) { - for (String key : set.keySet()) { - set.put(key, Cast.asFloat(scope, set.get(key))* val ); - } - return set; - } - - - protected ParametersSet sub(IScope scope, ParametersSet set1, ParametersSet set2) { - for (String key : set1.keySet()) { - set1.put(key, Cast.asFloat(scope, set1.get(key))- Cast.asFloat(scope, set2.get(key)) ); - } - return set1; - } - - protected ParametersSet add(IScope scope,ParametersSet set1, ParametersSet set2) { - for (String key : set1.keySet()) { - set1.put(key, Cast.asFloat(scope, set1.get(key)) + Cast.asFloat(scope, set2.get(key)) ); - } - return set1; - } } diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java b/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java index 660588f712..7808c8d784 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/BatchAgent.java @@ -1,11 +1,12 @@ /******************************************************************************************************* * - * BatchAgent.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * BatchAgent.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.experiment; @@ -80,9 +81,10 @@ public class BatchAgent extends ExperimentAgent { /** The fitness values. */ final List fitnessValues = new ArrayList<>(); - + + /** The tracked values. */ // GENERIC OUTPUTS - final Map trackedValues = new HashMap<>(); + final Map trackedValues = new HashMap<>(); /** * Instantiates a new batch agent. @@ -154,9 +156,7 @@ public void reset() { final boolean hasSimulations = pop != null && !pop.isEmpty(); try { if (hasSimulations) { - for (final IAgent sim : pop.toArray()) { - manageOutputAndCloseSimulation(sim,null,true,true); - } + for (final IAgent sim : pop.toArray()) { manageOutputAndCloseSimulation(sim, null, true, true); } pop.clear(); } @@ -174,50 +174,53 @@ public void reset() { ownClock.setTotalDuration(totalDuration); ownClock.setLastDuration(lastDuration); } - + // -------------------------------------------------------------------- // - // BATCH OUTPUT MANAGEMENT // + // BATCH OUTPUT MANAGEMENT // // -------------------------------------------------------------------- // /** * Retrieve output of interest from a batch simulation. Can be the specified fitness or any variables of interest. - * + * * @param sim * @param sol * @param memorize * @return */ - private IMap manageOutputAndCloseSimulation(final IAgent sim, ParametersSet sol, boolean memorize, boolean dispose) { + private IMap manageOutputAndCloseSimulation(final IAgent sim, final ParametersSet sol, + final boolean memorize, final boolean dispose) { IMap out = GamaMapFactory.create(); - if (getSpecies().getExplorationAlgorithm().isFitnessBased()) { - final IExpression fitness = ((AOptimizationAlgorithm) getSpecies().getExplorationAlgorithm()).getFitnessExpression(); + if (getSpecies().getExplorationAlgorithm().isFitnessBased()) { + final IExpression fitness = + ((AOptimizationAlgorithm) getSpecies().getExplorationAlgorithm()).getFitnessExpression(); double lastFitnessValue = 0; if (fitness != null) { lastFitnessValue = Cast.asFloat(sim.getScope(), fitness.value(sim.getScope())); - if (memorize) {fitnessValues.add(lastFitnessValue);} + if (memorize) { fitnessValues.add(lastFitnessValue); } } - out.put(IKeyword.FITNESS,lastFitnessValue); + out.put(IKeyword.FITNESS, lastFitnessValue); final FileOutput output = getSpecies().getLog(); if (output != null) { getSpecies().getLog().doRefreshWriteAndClose(sol, out); } } else { AExplorationAlgorithm exp = (AExplorationAlgorithm) getSpecies().getExplorationAlgorithm(); final IExpression outputs = exp.getOutputs(); - if (outputs!=null) { - final List outputVals = - GamaListFactory.create(sim.getScope(), Types.STRING, Cast.asList(sim.getScope(), outputs.value(sim.getScope()))); + if (outputs != null) { + final List outputVals = GamaListFactory.create(sim.getScope(), Types.STRING, + Cast.asList(sim.getScope(), outputs.value(sim.getScope()))); for (String s : outputVals) { Object v = sim.hasAttribute(s) ? sim.getDirectVarValue(getScope(), s) : null; - trackedValues.put(s, v); out.put(s, v); + trackedValues.put(s, v); + out.put(s, v); } final FileOutput output = getSpecies().getLog(); - if (output != null) { + if (output != null) { getSpecies().getLog().doRefreshWriteAndClose(sol, out); - if (!exp.getReport().equals("")) { getSpecies().getLog().doWriteReportAndClose(exp.getReport()); } + if (!"".equals(exp.getReport())) { getSpecies().getLog().doWriteReportAndClose(exp.getReport()); } } } } - - if (dispose) { sim.dispose(); } + + if (dispose) { sim.dispose(); } return out; } @@ -290,22 +293,22 @@ public IMap>> launchSimulationsWithSolut throws GamaRuntimeException { // We first reset the currentSolution and the fitness values final SimulationPopulation pop = getSimulationPopulation(); - /* Results gives for each "parameter set" (a point in the parameter space) a mapping between the key - * outputs of interest (as stated in facet 'outputs' or fitness if calibration process) and any - * results per repetition + /* + * Results gives for each "parameter set" (a point in the parameter space) a mapping between the key outputs of + * interest (as stated in facet 'outputs' or fitness if calibration process) and any results per repetition */ - IMap>> res = GamaMapFactory.create(); + IMap>> res = GamaMapFactory.create(); if (pop == null) return res; - + final List> sims = new ArrayList<>(); int numberOfCores = pop.getMaxNumberOfConcurrentSimulations(); if (numberOfCores == 0) { numberOfCores = 1; } - - // The values present in the solution are passed to the parameters of - // the experiment - for (ParametersSet sol :sols ) { - for (int i = 0; i < getSeeds().length ; i++) { + + // The values present in the solution are passed to the parameters of + // the experiment + for (ParametersSet sol : sols) { + for (int i = 0; i < getSeeds().length; i++) { Map sim = new HashMap<>(); sim.put("parameters", sol); sim.put("seed", getSeeds()[i]); @@ -337,20 +340,19 @@ public IMap>> launchSimulationsWithSolut final boolean mustStop = stopConditionMet || agent.dead() || agent.getScope().isPaused(); if (mustStop) { pop.unscheduleSimulation(agent); - //if (!getSpecies().keepsSimulations()) { - - IMap localRes = manageOutputAndCloseSimulation(agent, ps, false, !getSpecies().keepsSimulations()); - + // if (!getSpecies().keepsSimulations()) { + + IMap localRes = + manageOutputAndCloseSimulation(agent, ps, false, !getSpecies().keepsSimulations()); + if (!res.containsKey(ps)) { res.put(ps, GamaMapFactory.create()); } - for (String output : localRes.keySet()) { + for (String output : localRes.keySet()) { if (!res.get(ps).containsKey(output)) { res.get(ps).put(output, GamaListFactory.create()); } res.get(ps).get(output).add(localRes.get(output)); } - - if (!sims.isEmpty()) { - createSimulation(sims.remove(0), simToParameter); - } - + + if (!sims.isEmpty()) { createSimulation(sims.remove(0), simToParameter); } + } } // We then verify that the front scheduler has not been paused @@ -383,18 +385,19 @@ public IMap>> launchSimulationsWithSolut // different simulation. AOptimizationAlgorithm oAlgo = (AOptimizationAlgorithm) getSpecies().getExplorationAlgorithm(); final short fitnessCombination = oAlgo.getCombination(); - + for (ParametersSet p : res.keySet()) { lastSolution = p; - DoubleStream fit = res.get(p).get(IKeyword.FITNESS).stream().mapToDouble(o -> Double.valueOf(o.toString())); - lastFitness = fitnessCombination == AOptimizationAlgorithm.C_MAX ? fit.max().getAsDouble() - : fitnessCombination == AOptimizationAlgorithm.C_MIN ? fit.min().getAsDouble() - : fit.average().getAsDouble(); - fit.close(); - res.get(p).put(IKeyword.FITNESS, Arrays.asList(lastFitness)); + try (DoubleStream fit = + res.get(p).get(IKeyword.FITNESS).stream().mapToDouble(o -> Double.parseDouble(o.toString()))) { + lastFitness = fitnessCombination == AOptimizationAlgorithm.C_MAX ? fit.max().getAsDouble() + : fitnessCombination == AOptimizationAlgorithm.C_MIN ? fit.min().getAsDouble() + : fit.average().getAsDouble(); + } + res.get(p).put(IKeyword.FITNESS, Arrays.asList(lastFitness)); // we update the best solution found so far oAlgo.updateBestFitness(lastSolution, lastFitness); - + } } @@ -413,13 +416,14 @@ public IMap>> launchSimulationsWithSolut * @throws GamaRuntimeException * the gama runtime exception */ - public Map> launchSimulationsWithSolution(final ParametersSet sol) throws GamaRuntimeException { + public Map> launchSimulationsWithSolution(final ParametersSet sol) + throws GamaRuntimeException { // We first reset the currentSolution and the fitness values final SimulationPopulation pop = getSimulationPopulation(); Map> outputs = GamaMapFactory.create(); - + if (pop == null) return outputs; - + currentSolution = new ParametersSet(sol); fitnessValues.clear(); runNumber = runNumber + 1; @@ -461,8 +465,9 @@ public Map> launchSimulationsWithSolution(final ParametersS final boolean mustStop = stopConditionMet || agent.dead() || agent.getScope().isPaused(); if (mustStop) { pop.unscheduleSimulation(agent); - if (!getSpecies().keepsSimulations()) { - Map out = manageOutputAndCloseSimulation(agent,currentSolution,true,!getSpecies().keepsSimulations()); + if (!getSpecies().keepsSimulations()) { + Map out = manageOutputAndCloseSimulation(agent, currentSolution, true, + !getSpecies().keepsSimulations()); for (String out_vars : out.keySet()) { if (!outputs.containsKey(out_vars)) { outputs.put(out_vars, GamaListFactory.create()); } outputs.get(out_vars).add(out.get(out_vars)); @@ -505,7 +510,6 @@ public Map> launchSimulationsWithSolution(final ParametersS // simulations if any this.reset(); - if (getSpecies().getExplorationAlgorithm().isFitnessBased()) { // We then return the combination (average, min or max) of the different // fitness values computed by the @@ -515,7 +519,7 @@ public Map> launchSimulationsWithSolution(final ParametersS lastSolution = currentSolution; lastFitness = fitnessCombination == AOptimizationAlgorithm.C_MAX ? Collections.max(fitnessValues) : fitnessCombination == AOptimizationAlgorithm.C_MIN ? Collections.min(fitnessValues) - : Statistics.calculateMean(fitnessValues); + : Statistics.calculateMean(fitnessValues); outputs.put(IKeyword.FITNESS, GamaListFactory.createWithoutCasting(Types.FLOAT, lastFitness)); // we update the best solution found so far oAlgo.updateBestFitness(lastSolution, lastFitness); @@ -562,7 +566,7 @@ public List getDefaultParameters() { * the params */ public void addSpecificParameters(final List params) { - + params.add(new ParameterAdapter("Stop condition", IExperimentPlan.BATCH_CATEGORY_NAME, IType.STRING) { @Override @@ -603,9 +607,9 @@ int getExplorationDimension(final IParameter.Batch p) { }); - params.add(new ParameterAdapter("Last parameter set tested", IExperimentPlan.BATCH_CATEGORY_NAME, "", IType.STRING) { + params.add(new ParameterAdapter("Last parameter set tested", IExperimentPlan.BATCH_CATEGORY_NAME, "", + IType.STRING) { - @Override public String value() { if (lastSolution == null) return "-"; diff --git a/msi.gama.core/src/msi/gama/kernel/experiment/ParameterAdapter.java b/msi.gama.core/src/msi/gama/kernel/experiment/ParameterAdapter.java index 89e0306ec2..155a15ed79 100644 --- a/msi.gama.core/src/msi/gama/kernel/experiment/ParameterAdapter.java +++ b/msi.gama.core/src/msi/gama/kernel/experiment/ParameterAdapter.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.kernel.experiment.ParameterAdapter.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * ParameterAdapter.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.kernel.experiment; @@ -17,54 +17,78 @@ import msi.gama.runtime.IScope; import msi.gama.runtime.exceptions.GamaRuntimeException; import msi.gama.util.GamaColor; -import msi.gaml.descriptions.SymbolDescription; import msi.gaml.types.IType; import msi.gaml.types.Types; +import ummisco.gama.dev.utils.COUNTER; +/** + * The Class ParameterAdapter. + */ @SuppressWarnings ({ "rawtypes" }) public abstract class ParameterAdapter implements IParameter.Batch { - private final int order = SymbolDescription.ORDER++; + /** The order. */ + private final int order = COUNTER.GET(); + /** The title. */ protected String title; + + /** The type. */ protected final IType type; + + /** The category. */ protected String category; + + /** The unit label. */ protected String unitLabel; + /** + * Instantiates a new parameter adapter. + * + * @param title the title + * @param type the type + */ public ParameterAdapter(final String title, final int type) { this.title = title; this.type = Types.get(type); } + /** + * Instantiates a new parameter adapter. + * + * @param title the title + * @param category the category + * @param type the type + */ public ParameterAdapter(final String title, final String category, final int type) { this(title, type); this.category = category; } + /** + * Instantiates a new parameter adapter. + * + * @param title the title + * @param category the category + * @param unit the unit + * @param type the type + */ public ParameterAdapter(final String title, final String category, final String unit, final int type) { this(title, category, type); this.unitLabel = unit; } @Override - public int getOrder() { - return order; - } + public int getOrder() { return order; } @Override - public String getTitle() { - return title; - } + public String getTitle() { return title; } @Override - public String getName() { - return getTitle(); - } + public String getName() { return getTitle(); } @Override - public boolean isEditable() { - return false; - } + public boolean isEditable() { return false; } @Override public boolean canBeExplored() { @@ -75,9 +99,7 @@ public boolean canBeExplored() { public void setEditable(final boolean editable) {} @Override - public String getCategory() { - return category; - } + public String getCategory() { return category; } @Override public String getUnitLabel(final IScope scope) { @@ -93,9 +115,7 @@ public Object value(final IScope iScope) throws GamaRuntimeException { } @Override - public IType getType() { - return type; - } + public IType getType() { return type; } // @Override // public IType getContentType() { @@ -145,9 +165,7 @@ public Comparable getStepValue(final IScope scope) { } @Override - public void setCategory(final String name) { - category = name; - } + public void setCategory(final String name) { category = name; } /** * Method setUnitLabel() @@ -155,22 +173,16 @@ public void setCategory(final String name) { * @see msi.gama.kernel.experiment.IParameter#setUnitLabel(java.lang.String) */ @Override - public void setUnitLabel(final String label) { - unitLabel = label; - } + public void setUnitLabel(final String label) { unitLabel = label; } @Override - public boolean isDefined() { - return true; - } + public boolean isDefined() { return true; } @Override public void setDefined(final boolean defined) {} @Override - public boolean isDefinedInExperiment() { - return false; - } + public boolean isDefinedInExperiment() { return false; } @Override public boolean acceptsSlider(final IScope scope) { diff --git a/msi.gama.core/src/msi/gama/metamodel/shape/GamaShape.java b/msi.gama.core/src/msi/gama/metamodel/shape/GamaShape.java index 9a73d6bc63..9e47fabf39 100644 --- a/msi.gama.core/src/msi/gama/metamodel/shape/GamaShape.java +++ b/msi.gama.core/src/msi/gama/metamodel/shape/GamaShape.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.metamodel.shape.GamaShape.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * GamaShape.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.shape; @@ -54,28 +54,53 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaShape implements IShape { - class ShapeData { + /** + * The Class ShapeData. + */ + private static class ShapeData { + + /** The depth. */ private Double depth; + + /** The type. */ private Type type; } + /** The geometry. */ protected Geometry geometry; + + /** The agent. */ private IAgent agent; + + /** The attributes. */ protected IMap attributes; + /** + * Instantiates a new gama shape. + * + * @param geom the geom + */ public GamaShape(final Geometry geom) { setInnerGeometry(geom); } @Override - public IType getGamlType() { - return Types.GEOMETRY; - } + public IType getGamlType() { return Types.GEOMETRY; } + /** + * Instantiates a new gama shape. + * + * @param env the env + */ public GamaShape(final Envelope3D env) { this(env == null ? null : env.toGeometry()); } + /** + * Instantiates a new gama shape. + * + * @param geom the geom + */ public GamaShape(final IShape geom) { this(geom, null); @@ -109,9 +134,7 @@ private void mixAttributes(final IShape source) { final GamaShape shape = (GamaShape) source; if (shape.attributes != null) { getOrCreateAttributes(); - shape.attributes.forEach((key, val) -> { - if (val != source) { attributes.put(key, val); } - }); + shape.attributes.forEach((key, val) -> { if (val != source) { attributes.put(key, val); } }); } } else { // if (attr == null) { return; } @@ -225,10 +248,13 @@ public GamaShape(final IShape source, final Geometry geom, final AxisAngle rotat } @Override - public boolean isMultiple() { - return getInnerGeometry() instanceof GeometryCollection; - } + public boolean isMultiple() { return getInnerGeometry() instanceof GeometryCollection; } + /** + * Checks if is 3d. + * + * @return true, if is 3d + */ public boolean is3D() { return getDepth() != null; } @@ -275,9 +301,7 @@ public String serialize(final boolean includingBuiltIn) { result = "polygon (" + getPoints().serialize(includingBuiltIn) + ")"; } if (holes.isEmpty()) return result; - for (final GamaShape g : holes) { - result = "(" + result + ") - (" + g.serialize(includingBuiltIn) + ")"; - } + for (final GamaShape g : holes) { result = "(" + result + ") - (" + g.serialize(includingBuiltIn) + ")"; } return result; } @@ -302,18 +326,24 @@ public GamaPoint setLocation(final GamaPoint l) { return l; } + /** + * Translated to. + * + * @param scope the scope + * @param target the target + * @return the gama shape + */ public GamaShape translatedTo(final IScope scope, final GamaPoint target) { final GamaShape result = copy(scope); result.setLocation(target); return result; } + /** The Constant pl. */ public final static PointLocator pl = new PointLocator(); @Override - public GamaShape getGeometry() { - return this; - } + public GamaShape getGeometry() { return this; } @Override public Double getArea() { @@ -324,26 +354,23 @@ public Double getArea() { @Override public Double getVolume() { final Double d = getDepth(); - if (d == 0) - return 0d; - else { - final Type shapeType = getGeometricalType(); - // TODO : should put any specific shape volume calculation here !!! - switch (shapeType) { - case SPHERE: - return 4 / (double) 3 * Maths.PI * Maths.pow(getWidth() / 2.0, 3); - case CONE: - return 1 / (double) 3 * Maths.PI * Maths.pow(getWidth() / 2.0, 2) * d; - case PYRAMID: - return Maths.pow(getWidth(), 2) * d / 3; - case THREED_FILE: - case NULL: - final Envelope3D env3D = getEnvelope(); - return env3D == null ? Envelope3D.of(this.getGeometry().getInnerGeometry()).getVolume() - : env3D.getVolume(); - default: - return getArea() * d; - } + if (d == 0) return 0d; + final Type shapeType = getGeometricalType(); + // TODO : should put any specific shape volume calculation here !!! + switch (shapeType) { + case SPHERE: + return 4 / (double) 3 * Maths.PI * Maths.pow(getWidth() / 2.0, 3); + case CONE: + return 1 / (double) 3 * Maths.PI * Maths.pow(getWidth() / 2.0, 2) * d; + case PYRAMID: + return Maths.pow(getWidth(), 2) * d / 3; + case THREED_FILE: + case NULL: + final Envelope3D env3D = getEnvelope(); + return env3D == null ? Envelope3D.of(this.getGeometry().getInnerGeometry()).getVolume() + : env3D.getVolume(); + default: + return getArea() * d; } } @@ -402,29 +429,29 @@ public GamaShape getExteriorRing(final IScope scope) { return new GamaShape(result); } + /** + * Gets the data. + * + * @param createIt the create it + * @return the data + */ private ShapeData getData(final boolean createIt) { final Geometry g = getInnerGeometry(); if (g == null) return null; Object o = g.getUserData(); if (o == null) { - if (createIt) { - o = new ShapeData(); - g.setUserData(o); - } else - return null; + if (!createIt) return null; + o = new ShapeData(); + g.setUserData(o); } return (ShapeData) o; } @Override - public Double getWidth() { - return getEnvelope().getWidth(); - } + public Double getWidth() { return getEnvelope().getWidth(); } @Override - public Double getHeight() { - return getEnvelope().getHeight(); - } + public Double getHeight() { return getEnvelope().getHeight(); } @Override public Double getDepth() { @@ -439,9 +466,7 @@ public void setDepth(final double depth) { } @Override - public GamaShape getGeometricEnvelope() { - return new GamaShape(getEnvelope()); - } + public GamaShape getGeometricEnvelope() { return new GamaShape(getEnvelope()); } @Override public IList getPoints() { @@ -456,14 +481,10 @@ public Envelope3D getEnvelope() { } @Override - public IAgent getAgent() { - return agent; - } + public IAgent getAgent() { return agent; } @Override - public void setAgent(final IAgent a) { - agent = a; - } + public void setAgent(final IAgent a) { agent = a; } @Override public void setInnerGeometry(final Geometry geom) { @@ -487,6 +508,11 @@ public void setGeometry(final IShape geom) { mixAttributes(geom); } + /** + * Compute average Z ordinate. + * + * @return the double + */ private double computeAverageZOrdinate() { double z = 0d; final Coordinate[] coords = geometry.getCoordinates(); @@ -526,9 +552,7 @@ public int hashCode() { } @Override - public Geometry getInnerGeometry() { - return geometry; - } + public Geometry getInnerGeometry() { return geometry; } @Override public GamaShape copy(final IScope scope) { @@ -627,7 +651,7 @@ public boolean crosses(final IShape g) { return false; } } - + @Override public boolean partiallyOverlaps(final IShape g) { try { @@ -648,7 +672,7 @@ public boolean partiallyOverlaps(final IShape g) { return false; } } - + @Override public boolean touches(final IShape g) { try { diff --git a/msi.gama.core/src/msi/gama/metamodel/topology/graph/AStar.java b/msi.gama.core/src/msi/gama/metamodel/topology/graph/AStar.java index 7c863ca44d..499660d568 100644 --- a/msi.gama.core/src/msi/gama/metamodel/topology/graph/AStar.java +++ b/msi.gama.core/src/msi/gama/metamodel/topology/graph/AStar.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.metamodel.topology.graph.AStar.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * AStar.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.topology.graph; @@ -27,57 +27,115 @@ import msi.gama.util.graph._Vertex; import msi.gaml.types.Types; +/** + * The Class AStar. + * + * @param the value type + * @param the element type + */ public class AStar { + /** The graph. */ protected GamaGraph graph; + + /** The source. */ protected V source; + + /** The target. */ protected V target; + + /** The open map. */ protected Map openMap = GamaMapFactory.create(); + + /** The closed map. */ protected Map closedMap = GamaMapFactory.create(); + /** The result. */ protected List result; + + /** The is spatial graph. */ protected boolean isSpatialGraph; + + /** The is path found. */ protected boolean isPathFound = false; + /** + * Instantiates a new a star. + */ public AStar() {} + /** + * Instantiates a new a star. + * + * @param graph the graph + */ public AStar(final GamaGraph graph) { init(graph); } + /** + * Instantiates a new a star. + * + * @param graph the graph + * @param src the src + * @param trg the trg + */ public AStar(final GamaGraph graph, final V src, final V trg) { this(graph); setSource(src); setTarget(trg); } + /** + * Sets the source. + * + * @param node the new source + */ public void setSource(final V node) { cleanAll(); source = node; } + /** + * Sets the target. + * + * @param node the new target + */ public void setTarget(final V node) { cleanAll(); target = node; } + /** + * Inits the. + * + * @param graph the graph + */ public void init(final GamaGraph graph) { cleanAll(); this.graph = graph; isSpatialGraph = graph instanceof GamaSpatialGraph; } + /** + * Compute. + * + * @return the i list + */ public IList compute() { - if (source != null && target != null) { - aStar(source, target); - } - if (result == null || result.isEmpty()) - return GamaListFactory.EMPTY_LIST; - + if (source != null && target != null) { aStar(source, target); } + if (result == null || result.isEmpty()) return GamaListFactory.EMPTY_LIST; + return GamaListFactory.create(GAMA.getRuntimeScope(), Types.NO_TYPE, result); - + } + /** + * Builds the path. + * + * @param target the target + * @return the i list + */ public IList buildPath(final ASNode target) { try (final Collector.AsList path = Collector.getList(); @@ -104,6 +162,9 @@ public IList buildPath(final ASNode target) { } } + /** + * Clean all. + */ protected void cleanAll() { openMap.clear(); closedMap.clear(); @@ -112,6 +173,12 @@ protected void cleanAll() { isPathFound = false; } + /** + * A star. + * + * @param sourceNode the source node + * @param targetNode the target node + */ @SuppressWarnings ("unchecked") protected void aStar(final V sourceNode, final V targetNode) { cleanAll(); @@ -139,32 +206,40 @@ protected void aStar(final V sourceNode, final V targetNode) { for (final E edge : edges) { final _Edge eg = graph.getEdge(edge); final V next = (V) (eg.getTarget().equals(current.node) ? eg.getSource() : eg.getTarget()); - if (closedMap.containsKey(next)) { - continue; - } + if (closedMap.containsKey(next)) { continue; } final double h = heuristic(next, targetNode); final double g = current.g + eg.getWeight(); final ASNode openNode = openMap.get(next); if (openNode == null || g < openNode.g) { openMap.put(next, new ASNode(next, edge, current, g, h)); - } else if (g >= openNode.rank) { - continue; - } + } else if (g >= openNode.rank) {} } } } + /** + * Heuristic. + * + * @param node1 the node 1 + * @param node2 the node 2 + * @return the double + */ protected double heuristic(final Object node1, final Object node2) { if (isSpatialGraph) { - final GamaPoint pt1 = (GamaPoint) ((IShape) node1).getLocation(); - final GamaPoint pt2 = (GamaPoint) ((IShape) node2).getLocation(); + final GamaPoint pt1 = ((IShape) node1).getLocation(); + final GamaPoint pt2 = ((IShape) node2).getLocation(); return pt1.distance(pt2); } return 0; } + /** + * Gets the next better node. + * + * @return the next better node + */ protected ASNode getNextBetterNode() { double min = Float.MAX_VALUE; ASNode theChosenOne = null; @@ -179,16 +254,36 @@ protected ASNode getNextBetterNode() { return theChosenOne; } + /** + * The Class ASNode. + */ protected class ASNode { + /** The node. */ public V node; + + /** The parent. */ public ASNode parent; + + /** The edge. */ public E edge; + + /** The g. */ public double g; // public double h; + /** The rank. */ public double rank; + /** + * Instantiates a new AS node. + * + * @param node the node + * @param edge the edge + * @param parent the parent + * @param g the g + * @param h the h + */ public ASNode(final V node, final E edge, final ASNode parent, final double g, final double h) { this.node = node; this.edge = edge; diff --git a/msi.gama.core/src/msi/gama/metamodel/topology/graph/GraphTopology.java b/msi.gama.core/src/msi/gama/metamodel/topology/graph/GraphTopology.java index 90d1f7f5d6..c684757031 100644 --- a/msi.gama.core/src/msi/gama/metamodel/topology/graph/GraphTopology.java +++ b/msi.gama.core/src/msi/gama/metamodel/topology/graph/GraphTopology.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.metamodel.topology.graph.GraphTopology.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * GraphTopology.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -23,7 +23,6 @@ import msi.gama.common.preferences.GamaPreferences; import msi.gama.metamodel.agent.IAgent; import msi.gama.metamodel.shape.GamaPoint; - import msi.gama.metamodel.shape.IShape; import msi.gama.metamodel.topology.AbstractTopology; import msi.gama.metamodel.topology.ITopology; @@ -62,6 +61,14 @@ public GraphTopology(final IScope scope, final IShape env, final GamaSpatialGrap places = graph; } + /** + * Instantiates a new graph topology. + * + * @param scope + * the scope + * @param graph + * the graph + */ // The default topologies for graphs. public GraphTopology(final IScope scope, final GamaSpatialGraph graph) { this(scope, scope.getSimulation().getGeometry(), graph); @@ -73,10 +80,17 @@ protected boolean canCreateAgents() { } @Override - public boolean isContinuous() { - return false; - } + public boolean isContinuous() { return false; } + /** + * Optimized closest to. + * + * @param source + * the source + * @param candidates + * the candidates + * @return the i shape + */ private IShape optimizedClosestTo(final IShape source, final List candidates) { IShape result = null; final GamaPoint loc = source.getLocation(); @@ -137,15 +151,12 @@ public GamaSpatialPath pathBetween(final IScope scope, final IShape source, fina targetN = (IShape) ed; targetNode = true; } - if (sourceNode && targetNode) { - break; - } + if (sourceNode && targetNode) { break; } } } - if (sourceNode && targetNode) { + if (sourceNode && targetNode) return (GamaSpatialPath) graph.computeShortestPathBetween(scope, sourceN, targetN); - } IShape edgeS = null, edgeT = null; final boolean optimization = graph.edgeSet().size() > 1000; @@ -180,7 +191,7 @@ public GamaSpatialPath pathBetween(final IScope scope, final IShape source, fina } } // We avoid computing the target if we cannot find any source. - if (edgeS == null) { return null; } + if (edgeS == null) return null; } if (!targetNode) { // edgeT = getPathEdge(scope, target); @@ -205,15 +216,13 @@ public GamaSpatialPath pathBetween(final IScope scope, final IShape source, fina edgeT = scope.getSimulation().getAgent().getTopology().getAgentClosestTo(scope, target, filter); } - if (edgeT == null) { return null; } + if (edgeT == null) return null; } } else { double distSMin = Double.MAX_VALUE; double distTMin = Double.MAX_VALUE; edgeS = getPathEdge(scope, source); - if (edgeS != null) { - distSMin = 0; - } + if (edgeS != null) { distSMin = 0; } /* * edgeT = getPathEdge(scope, target); if (edgeT != null) distTMin = 0; */ @@ -241,7 +250,7 @@ public GamaSpatialPath pathBetween(final IScope scope, final IShape source, fina } } } - if (!sourceNode && edgeS == null || !targetNode && edgeT == null) { return null; } + if (!sourceNode && edgeS == null || !targetNode && edgeT == null) return null; } if (getPlaces().isDirected()) { @@ -268,26 +277,54 @@ public GamaSpatialPath pathBetween(final IScope scope, final IShape source, fina return pathBetweenCommon(scope, graph, edgeS, edgeT, sourceN, targetN, sourceNode, targetNode); } + /** + * Gets the path edge. + * + * @param scope + * the scope + * @param ref + * the ref + * @return the path edge + */ public IShape getPathEdge(final IScope scope, final IShape ref) { if (ref.getAgent() != null) { final IShape edge = (IShape) ref.getAgent().getAttribute("current_edge"); if (edge != null && this.getPlaces().containsEdge(edge) - && ref.getLocation().euclidianDistanceTo(edge) < 0.1) { + && ref.getLocation().euclidianDistanceTo(edge) < 0.1) return edge; - } final IPath path = (GamaPath) ref.getAgent().getAttribute("current_path"); - if (path != null && path.getTopology(scope) != null && path.getTopology(scope).equals(this) + if (path != null && path.getTopology(scope) != null && this.equals(path.getTopology(scope)) && ((IShape) path.getStartVertex()).getLocation().equals(ref.getLocation())) { final int index = path.indexOf(ref.getAgent()); - if (index >= path.getEdgeList().size()) { + if (index >= path.getEdgeList().size()) return (IShape) path.getEdgeList().get(path.getEdgeList().size() - 1); - } return (IShape) path.getEdgeList().get(index); } } return null; } + /** + * Path between common. + * + * @param scope + * the scope + * @param graph + * the graph + * @param edgeS + * the edge S + * @param edgeT + * the edge T + * @param source + * the source + * @param target + * the target + * @param sourceNode + * the source node + * @param targetNode + * the target node + * @return the gama spatial path + */ public GamaSpatialPath pathBetweenCommon(final IScope scope, final GamaSpatialGraph graph, final IShape edgeS, final IShape edgeT, final IShape source, final IShape target, final boolean sourceNode, final boolean targetNode) { @@ -326,10 +363,8 @@ public GamaSpatialPath pathBetweenCommon(final IScope scope, final GamaSpatialGr l1 = l2; } } - if (l1 == Double.MAX_VALUE) { return null; } - if (edges.isEmpty() || edges.get(edges.size() - 1) != edgeT) { - edges.add(edgeT); - } + if (l1 == Double.MAX_VALUE) return null; + if (edges.isEmpty() || edges.get(edges.size() - 1) != edgeT) { edges.add(edgeT); } } else if (!sourceNode && targetNode) { final IShape nodeS1 = (IShape) graph.getEdgeSource(edgeS); final IShape nodeS2 = (IShape) graph.getEdgeTarget(edgeS); @@ -364,10 +399,8 @@ public GamaSpatialPath pathBetweenCommon(final IScope scope, final GamaSpatialGr l1 = l2; } } - if (l1 == Double.MAX_VALUE) { return null; } - if (edges.isEmpty() || edges.get(0) != edgeS) { - edges.add(0, edgeS); - } + if (l1 == Double.MAX_VALUE) return null; + if (edges.isEmpty() || edges.get(0) != edgeS) { edges.add(0, edgeS); } } else { final IShape nodeS1 = (IShape) graph.getEdgeSource(edgeS); final IShape nodeS2 = (IShape) graph.getEdgeTarget(edgeS); @@ -400,26 +433,20 @@ public GamaSpatialPath pathBetweenCommon(final IScope scope, final GamaSpatialGr computeS2T1 = false; final double val = lmin - els - getPlaces().getEdgeWeight(e0) + lengthEdge(edgeS, source, nodeS1, nodeS2); - if (valmin > val) { - valmin = val; - } + if (valmin > val) { valmin = val; } } if (ts2) { computeS1T2 = false; final double val = lmin - elt - getPlaces().getEdgeWeight(el) + lengthEdge(edgeT, target, nodeT1, nodeT2); - if (valmin > val) { - valmin = val; - } + if (valmin > val) { valmin = val; } } if (ts1 && ts2) { computeS2T2 = false; final double val = lmin - els - getPlaces().getEdgeWeight(e0) - elt - getPlaces().getEdgeWeight(el) + lengthEdge(edgeS, source, nodeS1, nodeS2) + lengthEdge(edgeT, target, nodeT1, nodeT2); - if (valmin > val) { - valmin = val; - } + if (valmin > val) { valmin = val; } } lmin = valmin; } @@ -449,18 +476,14 @@ public GamaSpatialPath pathBetweenCommon(final IScope scope, final GamaSpatialGr computeS2T2 = false; final double val = l2 - elt - getPlaces().getEdgeWeight(el) + lengthEdge(edgeT, target, nodeT1, nodeT2); - if (valmin > val) { - valmin = val; - } + if (valmin > val) { valmin = val; } } if (ts1 && ts2) { computeS1T2 = false; final double val = l2 - els - getPlaces().getEdgeWeight(e0) - elt - getPlaces().getEdgeWeight(el) + lengthEdge(edgeS, source, nodeS2, nodeS1) + lengthEdge(edgeT, target, nodeT1, nodeT2); - if (valmin > val) { - valmin = val; - } + if (valmin > val) { valmin = val; } } l2 = valmin; } @@ -491,9 +514,7 @@ public GamaSpatialPath pathBetweenCommon(final IScope scope, final GamaSpatialGr computeS2T2 = false; final double val = l2 - els - getPlaces().getEdgeWeight(e0) + lengthEdge(edgeS, source, nodeS1, nodeS2); - if (l2 > val) { - l2 = val; - } + if (l2 > val) { l2 = val; } } } @@ -519,25 +540,50 @@ public GamaSpatialPath pathBetweenCommon(final IScope scope, final GamaSpatialGr lmin = l2; } } - if (lmin == Double.MAX_VALUE) { return null; } - if (edges.isEmpty() || edges.get(0) != edgeS) { - edges.add(0, edgeS); - } + if (lmin == Double.MAX_VALUE) return null; + if (edges.isEmpty() || edges.get(0) != edgeS) { edges.add(0, edgeS); } - if (edges.get(edges.size() - 1) != edgeT) { - edges.add(edgeT); - } + if (edges.get(edges.size() - 1) != edgeT) { edges.add(edgeT); } } return PathFactory.newInstance(scope, this, source, target, edges); } + /** + * Path from edges undirected. + * + * @param scope + * the scope + * @param listOfEdges + * the list of edges + * @param edgeS + * the edge S + * @param edgeT + * the edge T + * @param source + * the source + * @param target + * the target + * @param sourceNode + * the source node + * @param targetNode + * the target node + * @param nodeS + * the node S + * @param nodeSbis + * the node sbis + * @param nodeT + * the node T + * @param computeOther + * the compute other + * @return the gama spatial path + */ GamaSpatialPath pathFromEdgesUndirected(final IScope scope, final IList listOfEdges, final IShape edgeS, final IShape edgeT, final IShape source, final IShape target, final boolean sourceNode, final boolean targetNode, final IShape nodeS, final IShape nodeSbis, final IShape nodeT, final boolean computeOther) { IList edges = listOfEdges; - if (edges.isEmpty() || edges.get(0) == null) { return null; } + if (edges.isEmpty() || edges.get(0) == null) return null; if (!sourceNode) { Set edgesSetInit = new LinkedHashSet(Arrays.asList(edges.get(0).getInnerGeometry().getCoordinates())); final Set edgesSetS = new LinkedHashSet(Arrays.asList(edgeS.getInnerGeometry().getCoordinates())); @@ -555,9 +601,7 @@ GamaSpatialPath pathFromEdgesUndirected(final IScope scope, final IList } else { edges = edgesbis; edgesSetInit = new LinkedHashSet(Arrays.asList(edges.get(0).getInnerGeometry().getCoordinates())); - if (!edgesSetS.equals(edgesSetInit)) { - edges.add(0, edgeS); - } + if (!edgesSetS.equals(edgesSetInit)) { edges.add(0, edgeS); } } } @@ -567,44 +611,76 @@ GamaSpatialPath pathFromEdgesUndirected(final IScope scope, final IList new LinkedHashSet(Arrays.asList(edges.get(edges.size() - 1).getInnerGeometry().getCoordinates())); final Set edgesSetT = new LinkedHashSet(Arrays.asList(edgeT.getInnerGeometry().getCoordinates())); - if (!edgesSetT.equals(edgesSetEnd)) { - edges.add(edgeT); - } + if (!edgesSetT.equals(edgesSetEnd)) { edges.add(edgeT); } } // return new GamaPath(this, source, target, edges); return PathFactory.newInstance(scope, this, source, target, edges); } + /** + * Pathlength edges. + * + * @param edges + * the edges + * @return the double + */ public double pathlengthEdges(final IList edges) { double length = 0; - for (final IShape sp : edges) { - length += getPlaces().getWeightOf(sp); - } + for (final IShape sp : edges) { length += getPlaces().getWeightOf(sp); } return length; } + /** + * Length edge. + * + * @param edge + * the edge + * @param location + * the location + * @param source + * the source + * @param target + * the target + * @return the double + */ public double lengthEdge(final IShape edge, final IShape location, final IShape source, final IShape target) { final double dist = source.getLocation().euclidianDistanceTo(target.getLocation()); return dist == 0 ? 0 : getPlaces().getWeightOf(edge) * location.euclidianDistanceTo(target.getLocation()) / dist; } + /** + * Path between common directed. + * + * @param scope + * the scope + * @param edgeS + * the edge S + * @param edgeT + * the edge T + * @param source + * the source + * @param target + * the target + * @param sourceNode + * the source node + * @param targetNode + * the target node + * @return the gama spatial path + */ public GamaSpatialPath pathBetweenCommonDirected(final IScope scope, final List edgeS, final List edgeT, final IShape source, final IShape target, final boolean sourceNode, final boolean targetNode) { - if (edgeS.size() == 1 && edgeT.size() == 1) { + if (edgeS.size() == 1 && edgeT.size() == 1) return pathBetweenCommonDirected(scope, edgeS.get(0), edgeT.get(0), source, target, sourceNode, targetNode); - } double wMin = Double.MAX_VALUE; GamaSpatialPath shortestPath = null; for (final IShape eS : edgeS) { for (final IShape eT : edgeT) { final GamaSpatialPath path = pathBetweenCommonDirected(scope, eS, eT, source, target, sourceNode, targetNode); - if (path == null) { - continue; - } + if (path == null) { continue; } final double weight = path.getWeight(); if (weight < wMin) { wMin = weight; @@ -616,6 +692,25 @@ public GamaSpatialPath pathBetweenCommonDirected(final IScope scope, final List< } + /** + * Path between common directed. + * + * @param scope + * the scope + * @param edgeS + * the edge S + * @param edgeT + * the edge T + * @param source + * the source + * @param target + * the target + * @param sourceNode + * the source node + * @param targetNode + * the target node + * @return the gama spatial path + */ public GamaSpatialPath pathBetweenCommonDirected(final IScope scope, final IShape edgeS, final IShape edgeT, final IShape source, final IShape target, final boolean sourceNode, final boolean targetNode) { IList edges; @@ -633,36 +728,39 @@ public GamaSpatialPath pathBetweenCommonDirected(final IScope scope, final IShap if (nodeS.equals(nodeT)) { edges = GamaListFactory.create(Types.GEOMETRY); - if (edgeS != null) { - edges.add(edgeS); - } - if (edgeT != null) { - edges.add(edgeT); - } + if (edgeS != null) { edges.add(edgeS); } + if (edgeT != null) { edges.add(edgeT); } return PathFactory.newInstance(scope, this, source, target, edges); } edges = getPlaces().computeBestRouteBetween(scope, nodeS, nodeT); - if (edges.isEmpty() || edges.get(0) == null) { return null; } + if (edges.isEmpty() || edges.get(0) == null) return null; - if (!sourceNode) { - edges.add(0, edgeS); - } - if (!targetNode) { - edges.add(edges.size(), edgeT); - } + if (!sourceNode) { edges.add(0, edgeS); } + if (!targetNode) { edges.add(edges.size(), edgeT); } // return new GamaPath(this, source, target, edges); return PathFactory.newInstance(scope, this, source, target, edges); } + /** + * Path between. + * + * @param scope + * the scope + * @param source + * the source + * @param target + * the target + * @param existingEdge + * the existing edge + * @return the gama spatial path + */ public GamaSpatialPath pathBetween(final IScope scope, final IShape source, final IShape target, final IShape existingEdge) { IList edges; if (source.equals(target)) { edges = GamaListFactory.create(Types.GEOMETRY); - if (existingEdge != null) { - edges.add(existingEdge); - } + if (existingEdge != null) { edges.add(existingEdge); } return PathFactory.newInstance(scope, this, source, target, edges); } edges = getPlaces().computeBestRouteBetween(scope, source, target); @@ -670,7 +768,7 @@ public GamaSpatialPath pathBetween(final IScope scope, final IShape source, fina edges = edges.listValue(scope, Types.NO_TYPE, true); edges.addValueAtIndex(scope, 0, existingEdge); } - if (edges.isEmpty() || edges.get(0) == null) { return null; } + if (edges.isEmpty() || edges.get(0) == null) return null; return PathFactory.newInstance(scope, this, source, target, edges); } @@ -709,9 +807,7 @@ protected ITopology _copy(final IScope scope) { */ @Override - public ISpatialGraph getPlaces() { - return (GamaSpatialGraph) super.getPlaces(); - } + public ISpatialGraph getPlaces() { return (GamaSpatialGraph) super.getPlaces(); } /** * @see msi.gama.environment.ITopology#isValidLocation(msi.gama.util.GamaPoint) @@ -727,10 +823,7 @@ public boolean isValidLocation(final IScope scope, final GamaPoint p) { @Override public boolean isValidGeometry(final IScope scope, final IShape g) { // Geometry g2 = g.getInnerGeometry(); - for (final IShape g1 : places.iterable(scope)) { - if (g1.intersects(g)) { return true; } - // TODO covers or intersects ? - } + for (final IShape g1 : places.iterable(scope)) { if (g1.intersects(g)) return true; } return false; } @@ -742,8 +835,8 @@ public boolean isValidGeometry(final IScope scope, final IShape g) { @Override public Double distanceBetween(final IScope scope, final IShape source, final IShape target) { final GamaSpatialPath path = this.pathBetween(scope, source, target); - if (path == null) { return Double.MAX_VALUE; } - if (path.getEdgeList().isEmpty()) { return 0.0; } + if (path == null) return Double.MAX_VALUE; + if (path.getEdgeList().isEmpty()) return 0.0; // Patrick: no idea of the goal of the following code (in commentary) /* @@ -760,8 +853,8 @@ public Double distanceBetween(final IScope scope, final IShape source, final ISh @Override public Double distanceBetween(final IScope scope, final GamaPoint source, final GamaPoint target) { final GamaSpatialPath path = this.pathBetween(scope, source, target); - if (path == null) { return Double.MAX_VALUE; } - if (path.getEdgeList().isEmpty()) { return 0.0; } + if (path == null) return Double.MAX_VALUE; + if (path.getEdgeList().isEmpty()) return 0.0; // Patrick: no idea of the goal of the following code (in commentary) /* * final Coordinate[] coordsSource = path.getEdgeList().get(0).getInnerGeometry().getCoordinates(); final @@ -820,13 +913,11 @@ public boolean isTorus() { @Override public IList KpathsBetween(final IScope scope, final IShape source, final IShape target, final int k) { final ISpatialGraph graph = getPlaces(); - if (source == target) { - return GamaListFactory.create(); - } + if (source == target) return GamaListFactory.create(); final boolean sourceNode = graph.containsVertex(source); final boolean targetNode = graph.containsVertex(target); - - if (sourceNode && targetNode) { return graph.computeKShortestPathsBetween(scope, source, target, k); } + + if (sourceNode && targetNode) return graph.computeKShortestPathsBetween(scope, source, target, k); IShape edgeS = null, edgeT = null; @@ -840,7 +931,7 @@ public IList KpathsBetween(final IScope scope, final IShape source, final IShape } // We avoid computing the target if we cannot find any source. - if (edgeS == null) { return null; } + if (edgeS == null) return null; } if (!targetNode) { if (getPlaces().getEdgeSpecies() != null) { @@ -848,16 +939,24 @@ public IList KpathsBetween(final IScope scope, final IShape source, final IShape } else { edgeT = shapeClosest(this.getPlaces().getEdges(), target); } - if (edgeT == null) { return null; } + if (edgeT == null) return null; } - if (getPlaces().isDirected()) { + if (getPlaces().isDirected()) return KpathsBetweenCommonDirected(scope, edgeS, edgeT, source, target, sourceNode, targetNode, k); - } return KpathsBetweenCommon(scope, edgeS, edgeT, source, target, sourceNode, targetNode, k); } + /** + * Shape closest. + * + * @param shapes + * the shapes + * @param geom + * the geom + * @return the i shape + */ public IShape shapeClosest(final List shapes, final IShape geom) { IShape cp = null; double distMin = Double.MAX_VALUE; @@ -877,6 +976,27 @@ public IList KpathsBetween(final IScope scope, final GamaPoint return KpathsBetween(scope, source.getGeometry(), target.getGeometry(), k); } + /** + * Kpaths between common. + * + * @param scope + * the scope + * @param edgeS + * the edge S + * @param edgeT + * the edge T + * @param source + * the source + * @param target + * the target + * @param sourceNode + * the source node + * @param targetNode + * the target node + * @param k + * the k + * @return the i list + */ public IList KpathsBetweenCommon(final IScope scope, final IShape edgeS, final IShape edgeT, final IShape source, final IShape target, final boolean sourceNode, final boolean targetNode, final int k) { IShape nodeS = source; @@ -888,7 +1008,7 @@ public IList KpathsBetweenCommon(final IScope scope, final IShape edgeS, final I IShape t2 = null; t1 = getPlaces().getEdgeSource(edgeT); t2 = getPlaces().getEdgeTarget(edgeT); - if (t1 == null || t2 == null) { return null; } + if (t1 == null || t2 == null) return null; nodeT = t1; if (t1.getLocation().euclidianDistanceTo(target.getLocation()) > t2.getLocation() .euclidianDistanceTo(target.getLocation())) { @@ -900,7 +1020,7 @@ public IList KpathsBetweenCommon(final IScope scope, final IShape edgeS, final I IShape s2 = null; s1 = getPlaces().getEdgeSource(edgeS); s2 = getPlaces().getEdgeTarget(edgeS); - if (s1 == null || s2 == null) { return null; } + if (s1 == null || s2 == null) return null; nodeS = s1; nodeSbis = s2; if (s1.equals(nodeT) || !s2.equals(nodeT) && s1.getLocation().euclidianDistanceTo(source.getLocation()) > s2 @@ -914,15 +1034,34 @@ public IList KpathsBetweenCommon(final IScope scope, final IShape edgeS, final I for (final IList edges : edgesList) { final GamaSpatialPath pp = pathFromEdgesUndirected(scope, edges, edgeS, edgeT, source, target, sourceNode, targetNode, nodeS, nodeSbis, nodeT, false); - if (pp != null) { - results.add(pp); - } + if (pp != null) { results.add(pp); } } Collections.sort(results); return results; } + /** + * Kpaths between common directed. + * + * @param scope + * the scope + * @param edgeS + * the edge S + * @param edgeT + * the edge T + * @param source + * the source + * @param target + * the target + * @param sourceNode + * the source node + * @param targetNode + * the target node + * @param k + * the k + * @return the i list + */ public IList KpathsBetweenCommonDirected(final IScope scope, final IShape edgeS, final IShape edgeT, final IShape source, final IShape target, final boolean sourceNode, final boolean targetNode, final int k) { final IList results = GamaListFactory.create(Types.PATH); @@ -951,22 +1090,14 @@ public IList KpathsBetweenCommonDirected(final IScope scope, final IShape edgeS, * TODO AD: PROBLEM HERE. Why is edges recomputed immediately ? */ edges = getPlaces().computeBestRouteBetween(scope, nodeS, nodeT); - if (edges.isEmpty() || edges.get(0) == null) { - continue; - } + if (edges.isEmpty() || edges.get(0) == null) { continue; } - if (!sourceNode) { - edges.add(0, edgeS); - } - if (!targetNode) { - edges.add(edges.size(), edgeT); - } + if (!sourceNode) { edges.add(0, edgeS); } + if (!targetNode) { edges.add(edges.size(), edgeT); } // return new GamaPath(this, source, target, edges); final GamaSpatialPath pp = PathFactory.newInstance(scope, this, source, target, edges); - if (pp != null) { - results.add(pp); - } + results.add(pp); } Collections.sort(results); return results; @@ -1005,16 +1136,15 @@ public Collection getNeighborsOf(final IScope scope, final IShape source searchVertices = filter.getSpecies() == graph.getVertexSpecies(); } if (searchEdges) { - final Set edgs = getNeighborsOfRec(scope, realS, true, distance, graph, new LinkedHashSet()); - for (final IShape ed : edgs) { - agents.add(ed.getAgent()); - } + final Set edgs = + getNeighborsOfRec(scope, realS, true, distance, graph, new LinkedHashSet()); + for (final IShape ed : edgs) { agents.add(ed.getAgent()); } return agents.items(); - } else if (searchVertices) { - final Set nds = getNeighborsOfRec(scope, realS, false, distance, graph, new LinkedHashSet()); - for (final IShape nd : nds) { - agents.add(nd.getAgent()); - } + } + if (searchVertices) { + final Set nds = + getNeighborsOfRec(scope, realS, false, distance, graph, new LinkedHashSet()); + for (final IShape nd : nds) { agents.add(nd.getAgent()); } return agents.items(); } IContainer agentsTotest = null; @@ -1023,7 +1153,8 @@ public Collection getNeighborsOf(final IScope scope, final IShape source } else { agentsTotest = scope.getSimulation().getAgents(scope); } - final Set edges = getNeighborsOfRec(scope, realS, true, distance, graph, new LinkedHashSet()); + final Set edges = + getNeighborsOfRec(scope, realS, true, distance, graph, new LinkedHashSet()); for (final Object ob : agentsTotest.iterable(scope)) { final IShape ag = (IShape) ob; if (filter.accept(scope, source, ag)) { @@ -1053,23 +1184,36 @@ public Collection getNeighborsOf(final IScope scope, final IShape source } + /** + * Gets the neighbors of rec. + * + * @param scope + * the scope + * @param currentSource + * the current source + * @param edge + * the edge + * @param currentDist + * the current dist + * @param graph + * the graph + * @param alr + * the alr + * @return the neighbors of rec + * @throws GamaRuntimeException + * the gama runtime exception + */ public Set getNeighborsOfRec(final IScope scope, final IShape currentSource, final boolean edge, final double currentDist, final ISpatialGraph graph, final Set alr) throws GamaRuntimeException { try (Collector.AsSet edges = Collector.getSet()) { final Set eds = graph.isDirected() ? graph.outgoingEdgesOf(currentSource) : graph.edgesOf(currentSource); - if (!edge) { - edges.add(currentSource.getAgent()); - } + if (!edge) { edges.add(currentSource.getAgent()); } for (final IShape ed : eds) { - if (alr.contains(ed)) { - continue; - } + if (alr.contains(ed)) { continue; } alr.add(ed); final double dist = getPlaces().getEdgeWeight(ed); - if (edge) { - edges.add(ed); - } + if (edge) { edges.add(ed); } if (currentDist - dist > 0) { IShape nextNode = null; if (graph.isDirected()) { @@ -1096,12 +1240,10 @@ public IAgent getAgentClosestTo(final IScope scope, final IShape source, final I double minDist = Double.POSITIVE_INFINITY; for (final IAgent ag : listAgents) { final Double dist = this.distanceBetween(scope, source, ag); - if (dist != null && dist < minDist) { + if (dist < minDist) { closest = ag; minDist = dist; - if (dist == 0) { - break; - } + if (dist == 0) { break; } } } diff --git a/msi.gama.core/src/msi/gama/metamodel/topology/graph/NBAStarPathfinder.java b/msi.gama.core/src/msi/gama/metamodel/topology/graph/NBAStarPathfinder.java index 22a0dfc384..9b445b4ac2 100644 --- a/msi.gama.core/src/msi/gama/metamodel/topology/graph/NBAStarPathfinder.java +++ b/msi.gama.core/src/msi/gama/metamodel/topology/graph/NBAStarPathfinder.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.metamodel.topology.graph.NBAStarPathfinder.java, in plugin msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v. 1.8.1) + * NBAStarPathfinder.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.topology.graph; @@ -42,35 +42,78 @@ */ public final class NBAStarPathfinder { + /** The opena. */ private final PriorityQueue> OPENA = new PriorityQueue<>(); + + /** The openb. */ private final PriorityQueue> OPENB = new PriorityQueue<>(); + + /** The parentsa. */ private final Map PARENTSA = new HashMap<>(); + + /** The parentsb. */ private final Map PARENTSB = new HashMap<>(); + + /** The distancea. */ private final Map DISTANCEA = new HashMap<>(); + + /** The distanceb. */ private final Map DISTANCEB = new HashMap<>(); + + /** The closed. */ private final Set CLOSED = new HashSet<>(); + + /** The vertices. */ private final Map> vertices = new IdentityHashMap<>(); + /** The stop when path found. */ private boolean stopWhenPathFound = false; + /** The f A. */ private double fA; + + /** The f B. */ private double fB; + + /** The best path length. */ private double bestPathLength; + + /** The touch node. */ private V touchNode; + + /** The source node. */ private V sourceNode; + + /** The target node. */ private V targetNode; + /** The graph. */ GamaGraph graph; + + /** The is spatial graph. */ boolean isSpatialGraph; + /** + * Instantiates a new NBA star pathfinder. + * + * @param graph the graph + * @param stopWhenPathFound the stop when path found + */ public NBAStarPathfinder(final GamaGraph graph, final boolean stopWhenPathFound) { this.graph = graph; isSpatialGraph = graph instanceof GamaSpatialGraph; this.stopWhenPathFound = stopWhenPathFound; } + /** + * Search. + * + * @param sourceNode the source node + * @param targetNode the target node + * @return the i list + */ public IList search(final V sourceNode, final V targetNode) { - if (sourceNode.equals(targetNode)) { return GamaListFactory.EMPTY_LIST; } + if (sourceNode.equals(targetNode)) return GamaListFactory.EMPTY_LIST; init(sourceNode, targetNode); @@ -82,20 +125,21 @@ public IList search(final V sourceNode, final V targetNode) { } } - if (touchNode == null) { return GamaListFactory.EMPTY_LIST; } + if (touchNode == null) return GamaListFactory.EMPTY_LIST; return tracebackPath(); } + /** + * Expand in forward direction. + */ @SuppressWarnings ("unchecked") private void expandInForwardDirection() { final V currentNode = OPENA.remove().getNode(); - if (CLOSED.contains(currentNode)) { return; } + if (CLOSED.contains(currentNode)) return; final _Vertex cv = graph.getVertex(currentNode); - if (cv == null) { - // TODO: add a "node not found in graph" log message + if (cv == null) // TODO: add a "node not found in graph" log message return; - } vertices.put(currentNode, cv); CLOSED.add(currentNode); @@ -116,9 +160,7 @@ private void expandInForwardDirection() { final _Edge eg = graph.getEdge(edge); final V childNode = (V) (graph.isDirected() ? eg.getTarget() : eg.getTarget().equals(currentNode) ? eg.getSource() : eg.getTarget()); - if (CLOSED.contains(childNode)) { - continue; - } + if (CLOSED.contains(childNode)) { continue; } final double tentativeDistance = DISTANCEA.get(currentNode) + eg.getWeight(); if (!DISTANCEA.containsKey(childNode) || DISTANCEA.get(childNode) > tentativeDistance) { @@ -133,28 +175,27 @@ private void expandInForwardDirection() { if (bestPathLength > pathLength) { bestPathLength = pathLength; touchNode = childNode; - if (stopWhenPathFound) { return; } + if (stopWhenPathFound) return; } } } } } - if (!OPENA.isEmpty()) { - fA = OPENA.peek().getDistance(); - } + if (!OPENA.isEmpty()) { fA = OPENA.peek().getDistance(); } } + /** + * Expand in backward direction. + */ @SuppressWarnings ("unchecked") private void expandInBackwardDirection() { final V currentNode = OPENB.remove().getNode(); - if (CLOSED.contains(currentNode)) { return; } + if (CLOSED.contains(currentNode)) return; final _Vertex cv = graph.getVertex(currentNode); - if (cv == null) { - // TODO: add a "node not found in graph" log message + if (cv == null) // TODO: add a "node not found in graph" log message return; - } vertices.put(currentNode, cv); CLOSED.add(currentNode); @@ -175,9 +216,7 @@ private void expandInBackwardDirection() { final _Edge eg = graph.getEdge(edge); final V parentNode = (V) (graph.isDirected() ? eg.getSource() : eg.getSource().equals(currentNode) ? eg.getTarget() : eg.getSource()); - if (CLOSED.contains(parentNode)) { - continue; - } + if (CLOSED.contains(parentNode)) { continue; } final double tentativeDistance = DISTANCEB.get(currentNode) + eg.getWeight(); if (!DISTANCEB.containsKey(parentNode) || DISTANCEB.get(parentNode) > tentativeDistance) { @@ -194,7 +233,7 @@ private void expandInBackwardDirection() { bestPathLength = pathLength; touchNode = parentNode; - if (stopWhenPathFound) { return; } + if (stopWhenPathFound) return; } } } @@ -202,11 +241,15 @@ private void expandInBackwardDirection() { } } - if (!OPENB.isEmpty()) { - fB = OPENB.peek().getDistance(); - } + if (!OPENB.isEmpty()) { fB = OPENB.peek().getDistance(); } } + /** + * Inits the. + * + * @param sourceNode the source node + * @param targetNode the target node + */ private void init(final V sourceNode, final V targetNode) { OPENA.clear(); OPENB.clear(); @@ -265,16 +308,11 @@ protected IList tracebackPath() { if (vcn == null) { final V cn2 = cn; final Optional ocn = vertices.keySet().stream().filter(a -> a.equals(cn2)).findFirst(); - if (ocn.isPresent()) { - vcn = vertices.get(ocn.get()); - } else { - return edgePath; - } + if (!ocn.isPresent()) return edgePath; + vcn = vertices.get(ocn.get()); } final List edges = new ArrayList(vcn.edgesTo(tn)); - if (!graph.isDirected()) { - edges.addAll(vertices.get(tn).edgesTo(cn)); - } + if (!graph.isDirected()) { edges.addAll(vertices.get(tn).edgesTo(cn)); } if (edges.size() == 1) { edgePath.add(edges.get(0)); } else if (edges.size() > 1) { @@ -301,23 +339,38 @@ protected IList tracebackPath() { * @author Rodion "rodde" Efremov * @version 1.6 (Oct 13, 2016) */ - final class HeapEntry implements Comparable> { + static final class HeapEntry implements Comparable> { + /** The node id. */ private final V nodeId; + + /** The distance. */ private final double distance; // The priority key. + /** + * Instantiates a new heap entry. + * + * @param nodeId the node id + * @param distance the distance + */ public HeapEntry(final V nodeId, final double distance) { this.nodeId = nodeId; this.distance = distance; } - public V getNode() { - return nodeId; - } + /** + * Gets the node. + * + * @return the node + */ + public V getNode() { return nodeId; } - public double getDistance() { - return distance; - } + /** + * Gets the distance. + * + * @return the distance + */ + public double getDistance() { return distance; } @Override public int compareTo(final HeapEntry o) { @@ -325,10 +378,17 @@ public int compareTo(final HeapEntry o) { } } + /** + * Estimate distance between. + * + * @param node1 the node 1 + * @param node2 the node 2 + * @return the double + */ public double estimateDistanceBetween(final V node1, final V node2) { if (isSpatialGraph) { - final GamaPoint pt1 = (GamaPoint) ((IShape) node1).getLocation(); - final GamaPoint pt2 = (GamaPoint) ((IShape) node2).getLocation(); + final GamaPoint pt1 = ((IShape) node1).getLocation(); + final GamaPoint pt2 = ((IShape) node2).getLocation(); return pt1.euclidianDistanceTo(pt2); } diff --git a/msi.gama.core/src/msi/gama/metamodel/topology/grid/FieldDiffuser.java b/msi.gama.core/src/msi/gama/metamodel/topology/grid/FieldDiffuser.java index 8772156ff9..c8a1656bd4 100644 --- a/msi.gama.core/src/msi/gama/metamodel/topology/grid/FieldDiffuser.java +++ b/msi.gama.core/src/msi/gama/metamodel/topology/grid/FieldDiffuser.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.metamodel.topology.grid.GridDiffuser.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * FieldDiffuser.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -26,6 +26,9 @@ import msi.gama.runtime.exceptions.GamaRuntimeException; import ummisco.gama.dev.utils.DEBUG; +/** + * The Class FieldDiffuser. + */ public class FieldDiffuser { static { @@ -34,6 +37,7 @@ public class FieldDiffuser { // static ThreadLocal CACHE = new ThreadLocal<>(); + /** The cache. */ static LoadingCache CACHE = CacheBuilder.newBuilder().build(new CacheLoader() { @@ -56,6 +60,13 @@ public FieldDiffuser load(final SimulationAgent sim) throws Exception { // return diffuser; // }); + /** + * Gets the diffuser. + * + * @param scope + * the scope + * @return the diffuser + */ public static FieldDiffuser getDiffuser(final IScope scope) { try { return CACHE.get(scope.getSimulation()); @@ -65,24 +76,55 @@ public static FieldDiffuser getDiffuser(final IScope scope) { return null; } + /** The diffusions map. */ protected final ListMultimap diffusionsMap = MultimapBuilder.hashKeys(10).arrayListValues().build(); + /** The context. */ protected DiffusionContext context; + + /** The diffusion. */ protected GridDiffusion diffusion; + + /** The proportion. */ private float proportion; // in case of "avoid_mask" + + /** The scope. */ final IScope scope; + + /** The output. */ double[] input, output; + /** + * The Class DiffusionContext. + */ // Structure of the Key for the map of diffusions. - private class DiffusionContext { + private static class DiffusionContext { + + /** The nb rows. */ int nbRows; + + /** The nb cols. */ int nbCols; + + /** The is torus. */ boolean isTorus; + + /** The target. */ IDiffusionTarget target; + + /** The var name. */ final String varName; - public DiffusionContext(final String var_name, final IDiffusionTarget pop) { + /** + * Instantiates a new diffusion context. + * + * @param var_name + * the var name + * @param pop + * the pop + */ + public DiffusionContext(final IScope scope, final String var_name, final IDiffusionTarget pop) { varName = var_name; nbRows = pop.getRows(scope); nbCols = pop.getCols(scope); @@ -104,13 +146,42 @@ public boolean equals(final Object obj) { } } - private class GridDiffusion { + /** + * The Class GridDiffusion. + */ + private static class GridDiffusion { + + /** The use convolution. */ public boolean useConvolution = true; + + /** The is gradient. */ public boolean isGradient; + + /** The diffusion matrix. */ public double[][] mask, diffusionMatrix; + + /** The min value. */ public double minValue; + + /** The avoid mask. */ public boolean avoidMask; + /** + * Instantiates a new grid diffusion. + * + * @param use_convolution + * the use convolution + * @param is_gradient + * the is gradient + * @param mat_diffu + * the mat diffu + * @param mask + * the mask + * @param min_value + * the min value + * @param avoid_mask + * the avoid mask + */ public GridDiffusion(final boolean use_convolution, final boolean is_gradient, final double[][] mat_diffu, final double[][] mask, final double min_value, final boolean avoid_mask) { useConvolution = use_convolution; @@ -122,15 +193,42 @@ public GridDiffusion(final boolean use_convolution, final boolean is_gradient, f } } + /** + * Compare arrays. + * + * @param array1 + * the array 1 + * @param array2 + * the array 2 + * @return true, if successful + */ public boolean compareArrays(final double[][] array1, final double[][] array2) { if (array1 == null) return array2 == null; if (array2 == null || array1.length != array2.length) return false; - for (int i = 0; i < array1.length; i++) { - if (!Arrays.equals(array1[i], array2[i])) return false; - } + for (int i = 0; i < array1.length; i++) { if (!Arrays.equals(array1[i], array2[i])) return false; } return true; } + /** + * Adds the diffusion. + * + * @param varDiffu + * the var diffu + * @param pop + * the pop + * @param method_diffu + * the method diffu + * @param isGradient + * the is gradient + * @param matDiffu + * the mat diffu + * @param theMask + * the the mask + * @param minValue + * the min value + * @param avoidMask + * the avoid mask + */ public void addDiffusion(final String varDiffu, final IDiffusionTarget pop, final boolean method_diffu, final boolean isGradient, final double[][] matDiffu, final double[][] theMask, final double minValue, final boolean avoidMask) { @@ -138,7 +236,7 @@ public void addDiffusion(final String varDiffu, final IDiffusionTarget pop, fina // + scope.getSimulation() + " for var " + varDiffu); final GridDiffusion newGridDiff = new GridDiffusion(method_diffu, isGradient, matDiffu, theMask, minValue, avoidMask); - final DiffusionContext keyValue = new DiffusionContext(varDiffu, pop); + final DiffusionContext keyValue = new DiffusionContext(scope, varDiffu, pop); if (diffusionsMap.containsKey(keyValue)) { final List listWithSameVar = diffusionsMap.get(keyValue); // try to mix diffusions if possible @@ -207,23 +305,40 @@ && compareArrays(gridToAnalyze.mask, newGridDiff.mask) diffusionsMap.put(keyValue, newGridDiff); } + /** + * Instantiates a new field diffuser. + * + * @param scope + * the scope + */ public FieldDiffuser(final IScope scope) { this.scope = scope; } + /** + * Load grid properties. + * + * @param pairVarGrid + * the pair var grid + */ public void loadGridProperties(final DiffusionContext pairVarGrid) { context = pairVarGrid; } + /** + * Load diff properties. + * + * @param gridDiff + * the grid diff + * @return true, if successful + */ public boolean loadDiffProperties(final GridDiffusion gridDiff) { diffusion = gridDiff; if (gridDiff.avoidMask) { // compute proportion proportion = 0; for (final double[] element : diffusion.diffusionMatrix) { - for (int j = 0; j < diffusion.diffusionMatrix[0].length; j++) { - proportion += element[j]; - } + for (int j = 0; j < diffusion.diffusionMatrix[0].length; j++) { proportion += element[j]; } } } @@ -232,6 +347,9 @@ public boolean loadDiffProperties(final GridDiffusion gridDiff) { } + /** + * Diffusion with convolution. + */ public void diffusionWithConvolution() { // default method : convolution @@ -310,6 +428,9 @@ public void diffusionWithConvolution() { } } + /** + * Diffusion with dot product. + */ public void diffusionWithDotProduct() { // dot product @@ -390,16 +511,16 @@ public void diffusionWithDotProduct() { } } + /** + * Finish diffusion. + */ public void finishDiffusion() { for (int i = 0; i < output.length; i++) { double valToPut = output[i]; if (valToPut == -Double.MAX_VALUE) { continue; } if (diffusion.isGradient) { - if (valToPut > input[i]) { - if (valToPut < diffusion.minValue) { valToPut = 0; } - } else { - continue; - } + if (valToPut <= input[i]) { continue; } + if (valToPut < diffusion.minValue) { valToPut = 0; } } else { valToPut = Math.max(valToPut, diffusion.minValue); } @@ -407,6 +528,13 @@ public void finishDiffusion() { } } + /** + * Diffuse. + * + * @return the object + * @throws GamaRuntimeException + * the gama runtime exception + */ public Object diffuse() throws GamaRuntimeException { if (scope == null || scope.interrupted()) return false; diffusionsMap.asMap().forEach((context, diffusions) -> { diff --git a/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridDiffuser.java b/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridDiffuser.java index f416a9f32e..b5f07ef5cf 100644 --- a/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridDiffuser.java +++ b/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridDiffuser.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.metamodel.topology.grid.GridDiffuser.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * GridDiffuser.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.topology.grid; @@ -26,22 +26,47 @@ import msi.gaml.operators.Cast; import msi.gaml.variables.IVariable; +/** + * The Class GridDiffuser. + */ public class GridDiffuser { + /** + * The Class PairVarGrid. + */ // Structure of the Key for our map. - private class PairVarGrid { + private static class PairVarGrid { + + /** The Var name. */ String Var_name; + + /** The Grid name. */ String Grid_name; + + /** The Nb rows. */ int NbRows; + + /** The Nb cols. */ int NbCols; + + /** The Is torus. */ boolean Is_torus; + + /** The Pop. */ IPopulation Pop; + /** + * Instantiates a new pair var grid. + * + * @param scope the scope + * @param var_name the var name + * @param pop the pop + */ public PairVarGrid(final IScope scope, final String var_name, final GridPopulation pop) { Var_name = var_name; Grid_name = pop.getName(); - NbRows = ((IGrid) pop.getTopology().getPlaces()).getRows(scope); - NbCols = ((IGrid) pop.getTopology().getPlaces()).getCols(scope); + NbRows = pop.getTopology().getPlaces().getRows(scope); + NbCols = pop.getTopology().getPlaces().getCols(scope); Is_torus = pop.getTopology().isTorus(); Pop = pop; } @@ -53,23 +78,49 @@ public int hashCode() { @Override public boolean equals(final Object obj) { - if (!(obj instanceof PairVarGrid)) { return false; } - if (obj == this) { return true; } + if (!(obj instanceof PairVarGrid)) return false; + if (obj == this) return true; final PairVarGrid otherGrid = (PairVarGrid) obj; return otherGrid.Var_name.equals(Var_name) && otherGrid.Grid_name.equals(Grid_name); } } + /** + * The Class GridDiffusion. + */ // Structure for the Value of our map - private class GridDiffusion { + private static class GridDiffusion { + + /** The Use convolution. */ public boolean Use_convolution = true; + + /** The Is gradient. */ public boolean Is_gradient; + + /** The Mat diffu. */ public double[][] Mask, Mat_diffu; + + /** The Scope. */ public IScope Scope; + + /** The Min value. */ public double Min_value; + + /** The Avoid mask. */ public boolean Avoid_mask; + /** + * Instantiates a new grid diffusion. + * + * @param scope the scope + * @param use_convolution the use convolution + * @param is_gradient the is gradient + * @param mat_diffu the mat diffu + * @param mask the mask + * @param min_value the min value + * @param avoid_mask the avoid mask + */ public GridDiffusion(final IScope scope, final boolean use_convolution, final boolean is_gradient, final double[][] mat_diffu, final double[][] mask, final double min_value, final boolean avoid_mask) { Scope = scope; @@ -82,32 +133,50 @@ public GridDiffusion(final IScope scope, final boolean use_convolution, final bo } } + /** + * Compare arrays. + * + * @param array1 the array 1 + * @param array2 the array 2 + * @return true, if successful + */ public boolean compareArrays(final double[][] array1, final double[][] array2) { boolean b = true; - if (array1 != null && array2 != null) { - if (array1.length != array2.length) { - b = false; - } else { - for (int i = 0; i < array2.length; i++) { - if (array1[i].length != array2[i].length) { - b = false; - } else { - for (int j = 0; j < array2[i].length; j++) { - if (array2[i][j] != array1[i][j]) { - b = false; - } + if (((array1 == null) || (array2 == null)) || (array1.length != array2.length)) { + b = false; + } else { + for (int i = 0; i < array2.length; i++) { + if (array1[i].length != array2[i].length) { + b = false; + } else { + for (int j = 0; j < array2[i].length; j++) { + if (array2[i][j] != array1[i][j]) { + b = false; + break; } } } } - } else { - b = false; } return b; } + /** The m diffusions. */ protected final Map> m_diffusions = new HashMap<>(); + /** + * Adds the diffusion. + * + * @param scope the scope + * @param varDiffu the var diffu + * @param pop the pop + * @param method_diffu the method diffu + * @param isGradient the is gradient + * @param matDiffu the mat diffu + * @param theMask the the mask + * @param minValue the min value + * @param avoidMask the avoid mask + */ public void addDiffusion(final IScope scope, final String varDiffu, final GridPopulation pop, final boolean method_diffu, final boolean isGradient, final double[][] matDiffu, final double[][] theMask, final double minValue, final boolean avoidMask) { @@ -185,25 +254,55 @@ && compareArrays(gridToAnalyze.Mask, newGridDiff.Mask) } } + /** The is torus. */ private boolean is_torus; + + /** The is gradient. */ private boolean is_gradient; + + /** The var diffu. */ private String var_diffu; + + /** The use convolution. */ // true for convolution, false for dot_product private boolean use_convolution = true; + + /** The mat diffu. */ // boolean m_initialized = false; double[][] mask, mat_diffu; + + /** The avoid mask. */ private boolean avoid_mask; + + /** The proportion. */ private float proportion; // in case of "avoid_mask", compute the + + /** The diffuser scope. */ // proportion. IScope diffuserScope; + /** The output. */ double[] input, output; + + /** The nb cols. */ int nbRows, nbCols; + + /** The min value. */ double min_value; + + /** The population. */ IPopulation population; + /** + * Instantiates a new grid diffuser. + */ public GridDiffuser() {} + /** + * Load grid properties. + * + * @param pairVarGrid the pair var grid + */ public void loadGridProperties(final PairVarGrid pairVarGrid) { nbRows = pairVarGrid.NbRows; nbCols = pairVarGrid.NbCols; @@ -212,6 +311,12 @@ public void loadGridProperties(final PairVarGrid pairVarGrid) { population = pairVarGrid.Pop; } + /** + * Load diff properties. + * + * @param gridDiff the grid diff + * @return true, if successful + */ public boolean loadDiffProperties(final GridDiffusion gridDiff) { mat_diffu = gridDiff.Mat_diffu; @@ -221,29 +326,28 @@ public boolean loadDiffProperties(final GridDiffusion gridDiff) { min_value = gridDiff.Min_value; diffuserScope = gridDiff.Scope; avoid_mask = gridDiff.Avoid_mask; - if (diffuserScope == null || diffuserScope.interrupted()) { return false; } + if (diffuserScope == null || diffuserScope.interrupted()) return false; if (avoid_mask) { // compute proportion proportion = 0; for (final double[] element : mat_diffu) { - for (int j = 0; j < mat_diffu[0].length; j++) { - proportion += element[j]; - } + for (int j = 0; j < mat_diffu[0].length; j++) { proportion += element[j]; } } } for (int i = 0; i < input.length; i++) { input[i] = Cast.asFloat(diffuserScope, population.get(diffuserScope, i).getDirectVarValue(diffuserScope, var_diffu)); - if (input[i] < min_value) { - input[i] = 0; - } + if (input[i] < min_value) { input[i] = 0; } } return true; } + /** + * Do diffusion with convolution. + */ public void doDiffusion_with_convolution() { // default method : convolution @@ -270,15 +374,11 @@ public void doDiffusion_with_convolution() { if (is_torus) { if (ii < 0) { ii = nbRows + ii; - } else if (ii >= nbRows) { - ii = ii - nbRows; - } + } else if (ii >= nbRows) { ii = ii - nbRows; } if (jj < 0) { jj = nbCols + jj; - } else if (jj >= nbCols) { - jj = jj - nbCols; - } + } else if (jj >= nbCols) { jj = jj - nbCols; } } // diffuse if the input value is in the grid, and if the // cell is not masked @@ -287,17 +387,15 @@ public void doDiffusion_with_convolution() { if (output[j * nbCols + i] == -Double.MAX_VALUE) { output[j * nbCols + i] = input[jj * nbCols + ii] * mat_diffu[kRows - m - 1][kCols - n - 1]; - } else { - if (is_gradient) { - if (output[j * nbCols + i] < input[jj * nbCols + ii] - * mat_diffu[kRows - m - 1][kCols - n - 1]) { - output[j * nbCols + i] = - input[jj * nbCols + ii] * mat_diffu[kRows - m - 1][kCols - n - 1]; - } - } else { - output[j * nbCols + i] += + } else if (is_gradient) { + if (output[j * nbCols + i] < input[jj * nbCols + ii] + * mat_diffu[kRows - m - 1][kCols - n - 1]) { + output[j * nbCols + i] = input[jj * nbCols + ii] * mat_diffu[kRows - m - 1][kCols - n - 1]; } + } else { + output[j * nbCols + i] += + input[jj * nbCols + ii] * mat_diffu[kRows - m - 1][kCols - n - 1]; } // undo the changes if "avoid_mask" and if the @@ -318,17 +416,16 @@ public void doDiffusion_with_convolution() { for (final int[] coord : non_masked_cells) { if (output[coord[1] * nbCols + coord[0]] == -Double.MAX_VALUE) { output[coord[1] * nbCols + coord[0]] = value_to_add; - } else { - if (!is_gradient) { - output[coord[1] * nbCols + coord[0]] += value_to_add; - } - } + } else if (!is_gradient) { output[coord[1] * nbCols + coord[0]] += value_to_add; } } } } } } + /** + * Do diffusion with dot product. + */ public void doDiffusion_with_dotProduct() { // dot product @@ -358,15 +455,11 @@ public void doDiffusion_with_dotProduct() { if (is_torus) { if (i < 0) { i = nbRows + i; - } else if (i >= nbRows) { - i = i - nbRows; - } + } else if (i >= nbRows) { i = i - nbRows; } if (j < 0) { j = nbCols + j; - } else if (j >= nbCols) { - j = j - nbCols; - } + } else if (j >= nbCols) { j = j - nbCols; } } // diffuse if the output value is in the grid if (i >= 0 && i < nbCols && j >= 0 && j < nbRows) { @@ -376,14 +469,12 @@ public void doDiffusion_with_dotProduct() { final double matrixValue = mat_diffu[m][n]; if (output[outputIndex] == -Double.MAX_VALUE) { output[outputIndex] = input[inputIndex] * matrixValue; - } else { - if (is_gradient) { - if (output[outputIndex] < input[inputIndex] * matrixValue) { - output[outputIndex] = input[inputIndex] * matrixValue; - } - } else { - output[outputIndex] += input[inputIndex] * matrixValue; + } else if (is_gradient) { + if (output[outputIndex] < input[inputIndex] * matrixValue) { + output[outputIndex] = input[inputIndex] * matrixValue; } + } else { + output[outputIndex] += input[inputIndex] * matrixValue; } // undo the changes if "avoid_mask" and if the @@ -404,11 +495,7 @@ public void doDiffusion_with_dotProduct() { for (final int[] coord : non_masked_cells) { if (output[coord[1] * nbCols + coord[0]] == -Double.MAX_VALUE) { output[coord[1] * nbCols + coord[0]] = value_to_add; - } else { - if (!is_gradient) { - output[coord[1] * nbCols + coord[0]] += value_to_add; - } - } + } else if (!is_gradient) { output[coord[1] * nbCols + coord[0]] += value_to_add; } } } } @@ -416,23 +503,22 @@ public void doDiffusion_with_dotProduct() { } } + /** + * Finish diffusion. + * + * @param scope the scope + * @param pop the pop + */ public void finishDiffusion(final IScope scope, final IPopulation pop) { final IVariable v = pop.getVar(var_diffu); - if (v == null) { return; } + if (v == null) return; for (int i = 0; i < output.length; i++) { double valToPut = output[i]; - if (valToPut == -Double.MAX_VALUE) { - continue; - } + if (valToPut == -Double.MAX_VALUE) { continue; } if (is_gradient) { - if (valToPut > input[i]) { - if (valToPut < min_value) { - valToPut = 0; - } - } else { - continue; - } + if (valToPut <= input[i]) { continue; } + if (valToPut < min_value) { valToPut = 0; } } else { valToPut = Math.max(valToPut, min_value); } @@ -456,6 +542,12 @@ public void finishDiffusion(final IScope scope, final IPopulation keySet = m_diffusions.keySet(); diff --git a/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridMooreNeighborhood.java b/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridMooreNeighborhood.java index 923f25f3a1..46703b1532 100644 --- a/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridMooreNeighborhood.java +++ b/msi.gama.core/src/msi/gama/metamodel/topology/grid/GridMooreNeighborhood.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.metamodel.topology.grid.GridMooreNeighborhood.java, in plugin msi.gama.core, is part of the source code of - * the GAMA modeling and simulation platform (v. 1.8.1) + * GridMooreNeighborhood.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.metamodel.topology.grid; @@ -21,6 +21,11 @@ */ public class GridMooreNeighborhood extends GridNeighborhood { + /** + * Instantiates a new grid moore neighborhood. + * + * @param gamaSpatialMatrix the gama spatial matrix + */ public GridMooreNeighborhood(final GamaSpatialMatrix gamaSpatialMatrix) { super(gamaSpatialMatrix); } @@ -29,35 +34,25 @@ public GridMooreNeighborhood(final GamaSpatialMatrix gamaSpatialMatrix) { protected Set getNeighborsAtRadius(final int placeIndex, final int radius) { final int y = placeIndex / this.matrix.numCols; final int x = placeIndex - y * this.matrix.numCols; - final Set v = new HashSet(radius + 1 * radius + 1); + final Set v = new HashSet<>(radius + 1 * radius + 1); int p; for (int i = 1 - radius; i < radius; i++) { p = this.matrix.getPlaceIndexAt(x + i, y - radius); - if (p != -1) { - v.add(p); - } + if (p != -1) { v.add(p); } p = this.matrix.getPlaceIndexAt(x - i, y + radius); - if (p != -1) { - v.add(p); - } + if (p != -1) { v.add(p); } } for (int i = -radius; i < radius + 1; i++) { p = this.matrix.getPlaceIndexAt(x - radius, y - i); - if (p != -1) { - v.add(p); - } + if (p != -1) { v.add(p); } p = this.matrix.getPlaceIndexAt(x + radius, y + i); - if (p != -1) { - v.add(p); - } + if (p != -1) { v.add(p); } } return v; } @Override - public boolean isVN() { - return false; - } + public boolean isVN() { return false; } /* * (non-Javadoc) diff --git a/msi.gama.core/src/msi/gama/outputs/ImageDisplaySurface.java b/msi.gama.core/src/msi/gama/outputs/ImageDisplaySurface.java index c561a88220..8ae39160a9 100644 --- a/msi.gama.core/src/msi/gama/outputs/ImageDisplaySurface.java +++ b/msi.gama.core/src/msi/gama/outputs/ImageDisplaySurface.java @@ -3,7 +3,7 @@ * ImageDisplaySurface.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform * (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -38,6 +38,7 @@ import msi.gama.outputs.display.LayerManager; import msi.gama.outputs.layers.IEventLayerListener; import msi.gama.precompiler.GamlAnnotations.display; +import msi.gama.precompiler.GamlAnnotations.doc; import msi.gama.runtime.GAMA; import msi.gama.runtime.IScope.IGraphicsScope; import msi.gama.runtime.exceptions.GamaRuntimeException; @@ -48,7 +49,13 @@ /** * The Class ImageDisplaySurface. */ -@display ("image") + +/** + * The Class ImageDisplaySurface. + */ +@display ( + value = "image") +@doc ("A display used to save the graphical representations of agents into image files") public class ImageDisplaySurface implements IDisplaySurface { /** The output. */ diff --git a/msi.gama.core/src/msi/gama/outputs/layers/GraphicLayerStatement.java b/msi.gama.core/src/msi/gama/outputs/layers/GraphicLayerStatement.java index 464c076ff7..8320b7a4df 100644 --- a/msi.gama.core/src/msi/gama/outputs/layers/GraphicLayerStatement.java +++ b/msi.gama.core/src/msi/gama/outputs/layers/GraphicLayerStatement.java @@ -3,7 +3,7 @@ * GraphicLayerStatement.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform * (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -28,6 +28,7 @@ import msi.gaml.factories.DescriptionFactory; import msi.gaml.statements.AspectStatement; import msi.gaml.types.IType; +import ummisco.gama.dev.utils.COUNTER; /** * The Class GraphicLayerStatement. @@ -110,9 +111,6 @@ public class GraphicLayerStatement extends AbstractLayerStatement { /** The aspect. */ AspectStatement aspect; - /** The Layer index. */ - static int LayerIndex; - /** * Instantiates a new graphic layer statement. * @@ -124,7 +122,7 @@ public class GraphicLayerStatement extends AbstractLayerStatement { public GraphicLayerStatement(final IDescription desc) throws GamaRuntimeException { super(desc); final IDescription d = - DescriptionFactory.create(IKeyword.ASPECT, desc, IKeyword.NAME, "graphic_aspect" + LayerIndex++); + DescriptionFactory.create(IKeyword.ASPECT, desc, IKeyword.NAME, "graphic_aspect" + COUNTER.GET()); aspect = new AspectStatement(d); } diff --git a/msi.gama.core/src/msi/gama/outputs/layers/LightStatement.java b/msi.gama.core/src/msi/gama/outputs/layers/LightStatement.java index 299c7ed97d..77efc58d88 100644 --- a/msi.gama.core/src/msi/gama/outputs/layers/LightStatement.java +++ b/msi.gama.core/src/msi/gama/outputs/layers/LightStatement.java @@ -3,7 +3,7 @@ * LightStatement.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform * (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -36,6 +36,7 @@ import msi.gaml.statements.AspectStatement; import msi.gaml.types.IType; import msi.gaml.types.Types; +import ummisco.gama.dev.utils.COUNTER; /** * The Class LightStatement. @@ -184,9 +185,6 @@ else if (typeString.compareTo("spot") == 0) {} /** The aspect. */ AspectStatement aspect; - /** The i. */ - static int i; - /** The update. */ boolean update = true; @@ -200,7 +198,8 @@ else if (typeString.compareTo("spot") == 0) {} */ public LightStatement(final IDescription desc) throws GamaRuntimeException { super(desc); - final IDescription d = DescriptionFactory.create(IKeyword.ASPECT, desc, IKeyword.NAME, "graphic_aspect" + i++); + final IDescription d = + DescriptionFactory.create(IKeyword.ASPECT, desc, IKeyword.NAME, "graphic_aspect" + COUNTER.GET()); aspect = new AspectStatement(d); } diff --git a/msi.gama.core/src/msi/gama/outputs/layers/charts/ChartJFreeChartOutputPie.java b/msi.gama.core/src/msi/gama/outputs/layers/charts/ChartJFreeChartOutputPie.java index 7416a0ba99..ef413c8afa 100644 --- a/msi.gama.core/src/msi/gama/outputs/layers/charts/ChartJFreeChartOutputPie.java +++ b/msi.gama.core/src/msi/gama/outputs/layers/charts/ChartJFreeChartOutputPie.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.outputs.layers.charts.ChartJFreeChartOutputPie.java, in plugin msi.gama.core, is part of the source code of - * the GAMA modeling and simulation platform (v. 1.8.1) + * ChartJFreeChartOutputPie.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation + * platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -35,8 +35,21 @@ import msi.gama.runtime.IScope; import msi.gaml.expressions.IExpression; +/** + * The Class ChartJFreeChartOutputPie. + */ public class ChartJFreeChartOutputPie extends ChartJFreeChartOutput { + /** + * Instantiates a new chart J free chart output pie. + * + * @param scope + * the scope + * @param name + * the name + * @param typeexp + * the typeexp + */ public ChartJFreeChartOutputPie(final IScope scope, final String name, final IExpression typeexp) { super(scope, name, typeexp); // TODO Auto-generated constructor stubs @@ -46,9 +59,9 @@ public ChartJFreeChartOutputPie(final IScope scope, final String name, final IEx @Override public void createChart(final IScope scope) { super.createChart(scope); - if (style.equals(IKeyword.THREE_D)) { + if (IKeyword.THREE_D.equals(style)) { chart = ChartFactory.createPieChart3D(getName(), null, false, true, false); - } else if (style.equals(IKeyword.RING)) { + } else if (IKeyword.RING.equals(style)) { chart = ChartFactory.createRingChart(getName(), null, false, true, false); } else { chart = ChartFactory.createPieChart(getName(), null, false, true, false); @@ -88,17 +101,15 @@ public void setDefaultPropertiesFromType(final IScope scope, final ChartDataSour public void initChart(final IScope scope, final String chartname) { super.initChart(scope, chartname); - final PiePlot pp = (PiePlot) chart.getPlot(); + final PiePlot pp = (PiePlot) chart.getPlot(); pp.setShadowXOffset(0); pp.setShadowYOffset(0); - if (!this.series_label_position.equals("none")) { + if (!"none".equals(this.series_label_position)) { pp.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {1} ({2})")); - if (axesColor != null) { - pp.setLabelLinkPaint(axesColor); - } + if (axesColor != null) { pp.setLabelLinkPaint(axesColor); } pp.setLabelFont(getTickFont()); } - if (this.series_label_position.equals("none")) { + if ("none".equals(this.series_label_position)) { pp.setLabelLinksVisible(false); pp.setLabelGenerator(null); @@ -135,11 +146,19 @@ protected AbstractRenderer createRenderer(final IScope scope, final String serie return newr; } + /** + * Reset renderer. + * + * @param scope + * the scope + * @param serieid + * the serieid + */ protected void resetRenderer(final IScope scope, final String serieid) { final ChartDataSeries myserie = this.getChartdataset().getDataSeries(scope, serieid); // final int myrow = IdPosition.get(serieid); if (myserie.getMycolor() != null) { - ((PiePlot) this.getJFChart().getPlot()).setSectionPaint(serieid, myserie.getMycolor()); + ((PiePlot) this.getJFChart().getPlot()).setSectionPaint(serieid, myserie.getMycolor()); } } @@ -148,10 +167,11 @@ protected void resetRenderer(final IScope scope, final String serieid) { protected void clearDataSet(final IScope scope) { // TODO Auto-generated method stub super.clearDataSet(scope); - final PiePlot plot = (PiePlot) this.chart.getPlot(); + final PiePlot plot = (PiePlot) this.chart.getPlot(); jfreedataset.clear(); - jfreedataset.add(0, new DefaultPieDataset()); - plot.setDataset((DefaultPieDataset) jfreedataset.get(0)); + DefaultPieDataset dd = new DefaultPieDataset<>(); + jfreedataset.add(0, dd); + plot.setDataset(dd); IdPosition.clear(); nbseries = 0; } @@ -160,17 +180,15 @@ protected void clearDataSet(final IScope scope) { protected void createNewSerie(final IScope scope, final String serieid) { // final ChartDataSeries dataserie = chartdataset.getDataSeries(scope, // serieid); - if(!IdPosition.containsKey(serieid)) { - final PiePlot plot = (PiePlot) this.chart.getPlot(); - + if (!IdPosition.containsKey(serieid)) { + @SuppressWarnings ("unchecked") final PiePlot plot = (PiePlot) this.chart.getPlot(); + // final DefaultPieDataset firstdataset = (DefaultPieDataset) // plot.getDataset(); - + nbseries++; IdPosition.put(serieid, nbseries - 1); - if (getStyle().equals(IKeyword.EXPLODED)) { - plot.setExplodePercent(serieid, 0.20); - } + if (IKeyword.EXPLODED.equals(getStyle())) { plot.setExplodePercent(serieid, 0.20); } } // DEBUG.LOG("new serie"+serieid+" at // "+IdPosition.get(serieid)+" jfds "+jfreedataset.size()+" datasc "+" @@ -182,7 +200,8 @@ protected void resetSerie(final IScope scope, final String serieid) { // TODO Auto-generated method stub final ChartDataSeries dataserie = chartdataset.getDataSeries(scope, serieid); - final DefaultPieDataset serie = (DefaultPieDataset) jfreedataset.get(0); + @SuppressWarnings ("unchecked") final DefaultPieDataset serie = + (DefaultPieDataset) jfreedataset.get(0); final ArrayList YValues = dataserie.getYValues(scope); if (YValues.size() > 0) { @@ -218,24 +237,20 @@ public void getModelCoordinatesInfo(final int xOnScreen, final int yOnScreen, fi final boolean xInt = xx % 1 == 0; final boolean yInt = yy % 1 == 0; String xTitle = xAxis.getLabel(); - if (StringUtils.isBlank(xTitle)) { - xTitle = "X"; - } + if (StringUtils.isBlank(xTitle)) { xTitle = "X"; } String yTitle = yAxis.getLabel(); - if (StringUtils.isBlank(yTitle)) { - yTitle = "Y"; - } + if (StringUtils.isBlank(yTitle)) { yTitle = "Y"; } sb.append(xTitle).append(" ").append(xInt ? (int) xx : String.format("%.2f", xx)); sb.append(" | ").append(yTitle).append(" ").append(yInt ? (int) yy : String.format("%.2f", yy)); return; - } else if (entity instanceof PieSectionEntity) { + } + if (entity instanceof PieSectionEntity) { final String title = ((PieSectionEntity) entity).getSectionKey().toString(); - final PieDataset data = ((PieSectionEntity) entity).getDataset(); + final PieDataset data = ((PieSectionEntity) entity).getDataset(); final int index = ((PieSectionEntity) entity).getSectionIndex(); final double xx = data.getValue(index).doubleValue(); final boolean xInt = xx % 1 == 0; sb.append(title).append(" ").append(xInt ? (int) xx : String.format("%.2f", xx)); - return; } else if (entity instanceof CategoryItemEntity) { final Comparable columnKey = ((CategoryItemEntity) entity).getColumnKey(); final String title = columnKey.toString(); @@ -244,7 +259,6 @@ public void getModelCoordinatesInfo(final int xOnScreen, final int yOnScreen, fi final double xx = data.getValue(rowKey, columnKey).doubleValue(); final boolean xInt = xx % 1 == 0; sb.append(title).append(" ").append(xInt ? (int) xx : String.format("%.2f", xx)); - return; } } diff --git a/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java b/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java index 84770fbd6a..d1634ea672 100644 --- a/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java +++ b/msi.gama.core/src/msi/gama/runtime/ExecutionScope.java @@ -3,7 +3,7 @@ * ExecutionScope.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform * (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -44,6 +44,7 @@ import msi.gaml.types.IType; import msi.gaml.types.ITypesManager; import msi.gaml.types.Types; +import ummisco.gama.dev.utils.COUNTER; /** * Class AbstractScope. @@ -58,9 +59,6 @@ public class ExecutionScope implements IScope { /** The Constant ATTRIBUTES. */ private static final String ATTRIBUTES = "%_attributes_%"; - /** The scope number. */ - private static int SCOPE_NUMBER = 0; - /** The scope name. */ private final String scopeName; @@ -105,9 +103,9 @@ static class SpecialContext { /** The current error. */ GamaRuntimeException currentError; - - /** The horizontal pixel context. */ - boolean horizontalPixelContext = false; + // + // /** The horizontal pixel context. */ + // boolean horizontalPixelContext = false; /** * Clear. @@ -193,7 +191,7 @@ public ExecutionScope(final ITopLevelAgent root, final String otherName, final I */ public ExecutionScope(final ITopLevelAgent root, final String otherName, final IExecutionContext context, final AgentExecutionContext agentContext, final SpecialContext specialContext) { - StringBuilder name = new StringBuilder("Scope #").append(++SCOPE_NUMBER); + StringBuilder name = new StringBuilder("Scope #").append(COUNTER.GET()); setRoot(root); if (root != null) { name.append(" of ").append(root.stringValue(root.getScope())); } name.append(otherName == null || otherName.isEmpty() ? "" : " (" + otherName + ")"); diff --git a/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java b/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java index 222f24c4fc..7038e63953 100644 --- a/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java +++ b/msi.gama.core/src/msi/gama/runtime/HeadlessListener.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * HeadlessListener.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform - * (v.1.8.2). + * HeadlessListener.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.runtime; @@ -106,7 +106,7 @@ public IMap> openWizard(final IScope scope, final S String t = (String) l.get(IKeyword.TITLE); initialValues.put(t, initialValuesPage); - IList ps = (IList) l.get(IKeyword.PARAMETERS); + @SuppressWarnings ("unchecked") IList ps = (IList) l.get(IKeyword.PARAMETERS); if (ps != null) { ps.forEach(p -> { initialValuesPage.put(p.getName(), p.getInitialValue(scope)); }); } } diff --git a/msi.gama.core/src/msi/gama/runtime/MemoryUtils.java b/msi.gama.core/src/msi/gama/runtime/MemoryUtils.java index fd24393cc2..b615ac4892 100644 --- a/msi.gama.core/src/msi/gama/runtime/MemoryUtils.java +++ b/msi.gama.core/src/msi/gama/runtime/MemoryUtils.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * MemoryUtils.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform - * (v.1.8.2). + * MemoryUtils.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.runtime; @@ -254,14 +254,16 @@ public static File findIniFile() { */ public static File findIt(final File rootDir) { File[] files = rootDir.listFiles(); - List directories = new ArrayList<>(files.length); - for (File file : files) { - if ("Gama.ini".equals(file.getName())) return file; - if (file.isDirectory()) { directories.add(file); } - } - for (File directory : directories) { - File file = findIt(directory); - if (file != null) return file; + if (files != null) { + List directories = new ArrayList<>(files.length); + for (File file : files) { + if ("Gama.ini".equals(file.getName())) return file; + if (file.isDirectory()) { directories.add(file); } + } + for (File directory : directories) { + File file = findIt(directory); + if (file != null) return file; + } } return null; } diff --git a/msi.gama.core/src/msi/gama/runtime/PlatformHelper.java b/msi.gama.core/src/msi/gama/runtime/PlatformHelper.java index 24af4bbc0e..21078b16cd 100644 --- a/msi.gama.core/src/msi/gama/runtime/PlatformHelper.java +++ b/msi.gama.core/src/msi/gama/runtime/PlatformHelper.java @@ -3,7 +3,7 @@ * PlatformHelper.java, in msi.gama.core, is part of the source code of the * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -36,9 +36,9 @@ public class PlatformHelper { /** The is linux. */ private static boolean isLinux = "linux".equals(platformString); - + /** The is developer. */ - private static Boolean isDeveloper; + private static volatile Boolean isDeveloper; /** * Instantiates a new platform helper. @@ -90,7 +90,8 @@ public static boolean isDeveloper() { // NO_UCD (unused code) /** * Parses the version. * - * @param version the version + * @param version + * the version * @return the int */ static int parseVersion(final String version) { diff --git a/msi.gama.core/src/msi/gama/runtime/benchmark/Benchmark.java b/msi.gama.core/src/msi/gama/runtime/benchmark/Benchmark.java index 7200d79917..a0fc4fcd47 100644 --- a/msi.gama.core/src/msi/gama/runtime/benchmark/Benchmark.java +++ b/msi.gama.core/src/msi/gama/runtime/benchmark/Benchmark.java @@ -1,12 +1,11 @@ /******************************************************************************************************* * - * msi.gama.runtime.benchmark.Benchmark.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * Benchmark.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.runtime.benchmark; @@ -17,36 +16,85 @@ import msi.gama.runtime.IScope; import msi.gama.runtime.benchmark.Benchmark.ScopeRecord; +/** + * The Class Benchmark. + */ public class Benchmark extends ConcurrentHashMap { - class ScopeRecord extends ConcurrentHashMap { + /** + * The Class ScopeRecord. + */ + public static class ScopeRecord extends ConcurrentHashMap { + /** The own record. */ final BenchmarkRecord ownRecord; + /** + * Instantiates a new scope record. + * + * @param scope + * the scope + */ public ScopeRecord(final IScope scope) { ownRecord = new BenchmarkRecord(scope); } + /** + * Find. + * + * @param object + * the object + * @return the benchmark record + */ public BenchmarkRecord find(final IBenchmarkable object) { - return computeIfAbsent(object, (o) -> new BenchmarkRecord(o)); + return computeIfAbsent(object, BenchmarkRecord::new); } + /** + * Gets the stop watch for. + * + * @param desc + * the desc + * @return the stop watch for + */ public StopWatch getStopWatchFor(final IBenchmarkable desc) { return new StopWatch(ownRecord, find(desc)); } } + /** The tree. */ public final BenchmarkTree tree; + /** + * Instantiates a new benchmark. + * + * @param experiment + * the experiment + */ public Benchmark(final IExperimentPlan experiment) { tree = new BenchmarkTree(experiment.getModel().getDescription(), experiment.getDescription()); } + /** + * Record. + * + * @param scope + * the scope + * @param symbol + * the symbol + * @return the stop watch + */ public StopWatch record(final IScope scope, final IBenchmarkable symbol) { - return computeIfAbsent(scope, (s) -> new ScopeRecord(s)).getStopWatchFor(symbol).start(); + return computeIfAbsent(scope, ScopeRecord::new).getStopWatchFor(symbol).start(); } + /** + * Save and dispose. + * + * @param experiment + * the experiment + */ public void saveAndDispose(final IExperimentPlan experiment) { new BenchmarkConsolePrinter().print(this); new BenchmarkCSVExporter().save(experiment, this); diff --git a/msi.gama.core/src/msi/gama/runtime/exceptions/GamaRuntimeException.java b/msi.gama.core/src/msi/gama/runtime/exceptions/GamaRuntimeException.java index 452fa409e2..5b4c8ba761 100644 --- a/msi.gama.core/src/msi/gama/runtime/exceptions/GamaRuntimeException.java +++ b/msi.gama.core/src/msi/gama/runtime/exceptions/GamaRuntimeException.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.runtime.exceptions.GamaRuntimeException.java, in plugin msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v. 1.8.1) + * GamaRuntimeException.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.runtime.exceptions; @@ -33,13 +33,28 @@ public class GamaRuntimeException extends RuntimeException { + /** The cycle. */ private final long cycle; + + /** The agents names. */ protected final List agentsNames = new ArrayList<>(); + + /** The is warning. */ private boolean isWarning; + + /** The context. */ protected final List context = new ArrayList<>(); + + /** The editor context. */ protected EObject editorContext; + + /** The occurrences. */ protected int occurrences = 0; + + /** The reported. */ protected boolean reported = false; + + /** The scope. */ protected final IScope scope; // Factory methods @@ -51,25 +66,39 @@ public class GamaRuntimeException extends RuntimeException { */ public static GamaRuntimeException create(final Throwable ex, final IScope scope) { - if (ex instanceof GamaRuntimeException) { return (GamaRuntimeException) ex; } - if (ex instanceof IOException || ex instanceof FileNotFoundException) { + if (ex instanceof GamaRuntimeException) return (GamaRuntimeException) ex; + if (ex instanceof IOException || ex instanceof FileNotFoundException) return new GamaRuntimeFileException(scope, ex); - } return new GamaRuntimeException(scope, ex); } + /** + * Error. + * + * @param s the s + * @param scope the scope + * @return the gama runtime exception + */ public static GamaRuntimeException error(final String s, final IScope scope) { - final GamaRuntimeException ex = new GamaRuntimeException(scope, s, false); - return ex; + return new GamaRuntimeException(scope, s, false); } + /** + * Warning. + * + * @param s the s + * @param scope the scope + * @return the gama runtime exception + */ public static GamaRuntimeException warning(final String s, final IScope scope) { - final GamaRuntimeException ex = new GamaRuntimeException(scope, s, true); - return ex; + return new GamaRuntimeException(scope, s, true); } // Constructors + /** + * The Class GamaRuntimeFileException. + */ public static class GamaRuntimeFileException extends GamaRuntimeException { /** @@ -80,47 +109,61 @@ public GamaRuntimeFileException(final IScope scope, final Throwable ex) { super(scope, ex); } + /** + * Instantiates a new gama runtime file exception. + * + * @param scope the scope + * @param s the s + */ public GamaRuntimeFileException(final IScope scope, final String s) { super(scope, s, false); } } + /** + * Gets the exception name. + * + * @param ex the ex + * @return the exception name + */ protected static String getExceptionName(final Throwable ex) { final String s = ex.getClass().getName(); - if (s.contains("geotools") || s.contains("opengis")) { - return "exception in GeoTools library"; - } else if (s.contains("jts")) { + if (s.contains("geotools") || s.contains("opengis")) return "exception in GeoTools library"; + if (s.contains("jts")) return "exception in JTS library"; - } else if (s.contains("rcaller")) { + else if (s.contains("rcaller")) return "exception in RCaller library"; - } else if (s.contains("jogamp")) { + else if (s.contains("jogamp")) return "exception in JOGL library"; - } else if (s.contains("weka")) { + else if (s.contains("weka")) return "exception in Weka library"; - } else if (s.contains("math3")) { return "exception in Math library"; } - if (ex instanceof NullPointerException) { - return "nil value detected"; - } else if (ex instanceof IndexOutOfBoundsException) { + else if (s.contains("math3")) return "exception in Math library"; + if (ex instanceof NullPointerException) return "nil value detected"; + if (ex instanceof IndexOutOfBoundsException) return "index out of bounds"; - } else if (ex instanceof IOException) { + else if (ex instanceof IOException) return "I/O error"; - } else if (ex instanceof CoreException) { + else if (ex instanceof CoreException) return "exception in Eclipse"; - } else if (ex instanceof ClassCastException) { + else if (ex instanceof ClassCastException) return "wrong casting"; - } else if (ex instanceof IllegalArgumentException) { return "illegal argument"; } + else if (ex instanceof IllegalArgumentException) return "illegal argument"; return ex.getClass().getSimpleName(); } + /** + * Instantiates a new gama runtime exception. + * + * @param scope the scope + * @param ex the ex + */ protected GamaRuntimeException(final IScope scope, final Throwable ex) { super(ex == null ? "Unknown error" : "Java error: " + getExceptionName(ex), ex); if (scope != null) { final ISymbol symbol = scope.getCurrentSymbol(); - if (symbol != null) { - addContext(symbol); - } + if (symbol != null) { addContext(symbol); } } if (ex != null) { ex.printStackTrace(); @@ -128,9 +171,7 @@ protected GamaRuntimeException(final IScope scope, final Throwable ex) { int i = 0; for (final StackTraceElement element : ex.getStackTrace()) { addContext(element.toString()); - if (i++ > 5) { - break; - } + if (i++ > 5) { break; } } } cycle = computeCycle(scope); @@ -139,13 +180,18 @@ protected GamaRuntimeException(final IScope scope, final Throwable ex) { } + /** + * Instantiates a new gama runtime exception. + * + * @param scope the scope + * @param s the s + * @param warning the warning + */ protected GamaRuntimeException(final IScope scope, final String s, final boolean warning) { super(s); if (scope != null) { final ISymbol symbol = scope.getCurrentSymbol(); - if (symbol != null) { - addContext(symbol); - } + if (symbol != null) { addContext(symbol); } } cycle = computeCycle(scope); isWarning = warning; @@ -153,60 +199,101 @@ protected GamaRuntimeException(final IScope scope, final String s, final boolean this.scope = scope; } + /** + * Adds the context. + * + * @param c the c + */ public void addContext(final String c) { context.add(c); } + /** + * Adds the context. + * + * @param s the s + */ public void addContext(final ISymbol s) { addContext("in " + s.serialize(false)); final EObject e = s.getDescription().getUnderlyingElement(); - if (e != null) { - editorContext = e; - } + if (e != null) { editorContext = e; } } - public EObject getEditorContext() { - return editorContext; - } + /** + * Gets the editor context. + * + * @return the editor context + */ + public EObject getEditorContext() { return editorContext; } + /** + * Adds the agent. + * + * @param agent the agent + */ public void addAgent(final String agent) { occurrences++; - if (agentsNames.contains(agent)) { return; } + if (agentsNames.contains(agent)) return; agentsNames.add(agent); } + /** + * Adds the agents. + * + * @param agents the agents + */ public void addAgents(final List agents) { - for (final String agent : agents) { - addAgent(agent); - } + for (final String agent : agents) { addAgent(agent); } } - public long getCycle() { - return cycle; - } + /** + * Gets the cycle. + * + * @return the cycle + */ + public long getCycle() { return cycle; } + /** + * Gets the agent summary. + * + * @return the agent summary + */ public String getAgentSummary() { final int size = agentsNames.size(); final String agents = size == 0 ? "" : size == 1 ? agentsNames.get(0) : String.valueOf(size) + " agents"; - final String occurence = occurrences == 0 ? "" - : occurrences == 1 ? "1 occurence in " : String.valueOf(occurrences) + " occurrences in "; + final String occurence = occurrences == 0 ? "" : occurrences == 1 ? "1 occurence in " + : String.valueOf(occurrences) + " occurrences in "; return occurence + agents; } - public boolean isWarning() { - return isWarning; - } + /** + * Checks if is warning. + * + * @return true, if is warning + */ + public boolean isWarning() { return isWarning; } + /** + * Compute cycle. + * + * @param scope the scope + * @return the long + */ public long computeCycle(final IScope scope) { final SimulationClock clock = scope == null ? null : scope.getClock(); return clock == null ? 0l : clock.getCycle(); } + /** + * Gets the context as list. + * + * @return the context as list + */ public List getContextAsList() { final List result = new ArrayList<>(); result.addAll(context); final int size = agentsNames.size(); - if (size == 0) { return result; } + if (size == 0) return result; if (size == 1) { result.add("in agent " + agentsNames.get(0)); } else { @@ -231,25 +318,35 @@ public String toString() { return message != null ? message : s; } + /** + * Equivalent to. + * + * @param ex the ex + * @return true, if successful + */ public boolean equivalentTo(final GamaRuntimeException ex) { return this == ex || editorContext == ex.editorContext && getMessage().equals(ex.getMessage()) && getCycle() == ex.getCycle(); } + /** + * Sets the reported. + */ public void setReported() { reported = true; } - public boolean isReported() { - return reported; - } + /** + * Checks if is reported. + * + * @return true, if is reported + */ + public boolean isReported() { return reported; } /** * @return */ - public List getAgentsNames() { - return agentsNames; - } + public List getAgentsNames() { return agentsNames; } /** * @return @@ -257,17 +354,18 @@ public List getAgentsNames() { public String getAllText() { final StringBuilder sb = new StringBuilder(300); final String a = getAgentSummary(); - if (a != null) { - sb.append(a).append(" at "); - } + sb.append(a).append(" at "); sb.append("cycle ").append(getCycle()).append(": ").append(getMessage()); final List strings = getContextAsList(); - for (final String s : strings) { - sb.append(Strings.LN).append(s); - } + for (final String s : strings) { sb.append(Strings.LN).append(s); } return sb.toString(); } + /** + * Checks if is invalid. + * + * @return true, if is invalid + */ // If the simulation or experiment is dead, no need to report errors public boolean isInvalid() { return scope == null || scope instanceof ExecutionScope && ((ExecutionScope) scope)._root_interrupted(); diff --git a/msi.gama.core/src/msi/gama/util/GamaListFactory.java b/msi.gama.core/src/msi/gama/util/GamaListFactory.java index 3ff9e8d033..61b6966038 100644 --- a/msi.gama.core/src/msi/gama/util/GamaListFactory.java +++ b/msi.gama.core/src/msi/gama/util/GamaListFactory.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.util.GamaListFactory.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * GamaListFactory.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -50,11 +50,23 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaListFactory { + /** The Constant DEFAULT_SIZE. */ private static final int DEFAULT_SIZE = 4; + + /** The Constant EMPTY_LIST. */ public static final IList EMPTY_LIST = wrap(Types.NO_TYPE, Collections.EMPTY_LIST); + + /** The ch. */ static Set CH = ImmutableSet. of(Collector.Characteristics.IDENTITY_FINISH); + /** + * To gama list. + * + * @param + * the generic type + * @return the collector + */ public static Collector, IList> toGamaList() { return new Collector<>() { @@ -88,12 +100,23 @@ public Set characteristics() { }; } + /** The to gama list. */ public static Collector, IList> TO_GAMA_LIST = toGamaList(); + /** + * The Class GamaListSupplier. + */ public static class GamaListSupplier implements Supplier { + /** The t. */ final IType t; + /** + * Instantiates a new gama list supplier. + * + * @param t + * the t + */ public GamaListSupplier(final IType t) { this.t = t; } @@ -105,6 +128,17 @@ public IList get() { } + /** + * Creates the. + * + * @param + * the generic type + * @param t + * the t + * @param stream + * the stream + * @return the i list + */ public static IList create(final IType t, final Stream stream) { return (IList) stream.collect(TO_GAMA_LIST); } @@ -166,105 +200,216 @@ public static IList createWithoutCasting(final IType contentType, final I return list; } + /** + * Cast and add. + * + * @param scope + * the scope + * @param list + * the list + * @param o + * the o + */ private static void castAndAdd(final IScope scope, final IList list, final Object o) { list.addValue(scope, o); } + /** + * Creates the. + * + * @param scope + * the scope + * @param contentType + * the content type + * @param container + * the container + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final IContainer container) { if (container == null) return create(contentType); if (GamaType.requiresCasting(contentType, container.getGamlType().getContentType())) return create(scope, contentType, container.iterable(scope)); - else - return createWithoutCasting(contentType, container.iterable(scope)); + return createWithoutCasting(contentType, container.iterable(scope)); } + /** + * Creates the. + * + * @param + * the generic type + * @param scope + * the scope + * @param contentType + * the content type + * @param container + * the container + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final IList container) { if (container == null) return create(contentType); if (GamaType.requiresCasting(contentType, container.getGamlType().getContentType())) return create(scope, contentType, (Collection) container); - else - return createWithoutCasting(contentType, container); + return createWithoutCasting(contentType, container); } + /** + * Creates the. + * + * @param + * the generic type + * @param scope + * the scope + * @param contentType + * the content type + * @param iterable + * the iterable + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final Iterable iterable) { final IList list = create(contentType); - for (final Object o : iterable) { - castAndAdd(scope, list, o); - } + for (final Object o : iterable) { castAndAdd(scope, list, o); } return list; } + /** + * Creates the. + * + * @param + * the generic type + * @param scope + * the scope + * @param contentType + * the content type + * @param iterator + * the iterator + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final Iterator iterator) { final IList list = create(contentType); - if (iterator != null) { - while (iterator.hasNext()) { - castAndAdd(scope, list, iterator.next()); - } - } + if (iterator != null) { while (iterator.hasNext()) { castAndAdd(scope, list, iterator.next()); } } return list; } + /** + * Creates the. + * + * @param + * the generic type + * @param scope + * the scope + * @param contentType + * the content type + * @param iterator + * the iterator + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final Enumeration iterator) { final IList list = create(contentType); if (iterator != null) { - while (iterator.hasMoreElements()) { - castAndAdd(scope, list, iterator.nextElement()); - } + while (iterator.hasMoreElements()) { castAndAdd(scope, list, iterator.nextElement()); } } return list; } + /** + * Creates the. + * + * @param + * the generic type + * @param scope + * the scope + * @param contentType + * the content type + * @param objects + * the objects + * @return the i list + */ @SafeVarargs public static IList create(final IScope scope, final IType contentType, final T... objects) { final IList list = create(contentType, objects == null ? 0 : objects.length); - if (objects != null) { - for (final Object o : objects) { - castAndAdd(scope, list, o); - } - } + if (objects != null) { for (final Object o : objects) { castAndAdd(scope, list, o); } } return list; } + /** + * Creates the. + * + * @param scope + * the scope + * @param contentType + * the content type + * @param ints + * the ints + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final byte[] ints) { final IList list = create(contentType, ints == null ? 0 : ints.length); - if (ints != null) { - for (final int o : ints) { - castAndAdd(scope, list, Integer.valueOf(o)); - } - } + if (ints != null) { for (final int o : ints) { castAndAdd(scope, list, Integer.valueOf(o)); } } return list; } + /** + * Creates the. + * + * @param scope + * the scope + * @param contentType + * the content type + * @param ints + * the ints + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final int[] ints) { final IList list = create(contentType, ints == null ? 0 : ints.length); - if (ints != null) { - for (final int o : ints) { - castAndAdd(scope, list, Integer.valueOf(o)); - } - } + if (ints != null) { for (final int o : ints) { castAndAdd(scope, list, Integer.valueOf(o)); } } return list; } + /** + * Creates the. + * + * @param scope + * the scope + * @param contentType + * the content type + * @param ints + * the ints + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final long[] ints) { final IList list = create(contentType, ints == null ? 0 : ints.length); - if (ints != null) { - for (final long o : ints) { - castAndAdd(scope, list, Long.valueOf(o).intValue()); - } - } + if (ints != null) { for (final long o : ints) { castAndAdd(scope, list, Long.valueOf(o).intValue()); } } return list; } + /** + * Creates the. + * + * @param scope + * the scope + * @param contentType + * the content type + * @param doubles + * the doubles + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final float[] doubles) { final IList list = create(contentType, doubles == null ? 0 : doubles.length); - if (doubles != null) { - for (final float o : doubles) { - castAndAdd(scope, list, Double.valueOf(o)); - } - } + if (doubles != null) { for (final float o : doubles) { castAndAdd(scope, list, Double.valueOf(o)); } } return list; } + /** + * Creates the. + * + * @param scope + * the scope + * @param fillExpr + * the fill expr + * @param size + * the size + * @return the i list + */ public static IList create(final IScope scope, final IExpression fillExpr, final Integer size) { if (fillExpr == null) return create(Types.NO_TYPE, size); final Object[] contents = new Object[size]; @@ -272,32 +417,56 @@ public static IList create(final IScope scope, final IExpression fillExpr, final // 10/01/14. Cannot use Arrays.fill() everywhere: see Issue 778. if (fillExpr.isConst()) { final Object o = fillExpr.value(scope); - GamaExecutorService.executeThreaded(() -> IntStream.range(0, contents.length).parallel().forEach(i -> { - contents[i] = o; - })); - } else { GamaExecutorService.executeThreaded( - () -> IntStream.range(0, contents.length)./* see #2974. parallel(). */forEach(i -> { - contents[i] = fillExpr.value(scope); - })); + () -> IntStream.range(0, contents.length).parallel().forEach(i -> { contents[i] = o; })); + } else { + GamaExecutorService.executeThreaded(() -> IntStream.range(0, contents.length) + ./* see #2974. parallel(). */forEach(i -> { contents[i] = fillExpr.value(scope); })); } return create(scope, contentType, contents); } + /** + * Creates the. + * + * @param scope + * the scope + * @param contentType + * the content type + * @param doubles + * the doubles + * @return the i list + */ public static IList create(final IScope scope, final IType contentType, final double[] doubles) { final IList list = create(contentType, doubles == null ? 0 : doubles.length); - if (doubles != null) { - for (final double o : doubles) { - castAndAdd(scope, list, Double.valueOf(o)); - } - } + if (doubles != null) { for (final double o : doubles) { castAndAdd(scope, list, Double.valueOf(o)); } } return list; } + /** + * Creates the. + * + * @param + * the generic type + * @param contentType + * the content type + * @param size + * the size + * @return the i list + */ public static IList create(final IType contentType, final int size) { return new GamaList<>(size, contentType); } + /** + * Creates the. + * + * @param + * the generic type + * @param contentType + * the content type + * @return the i list + */ public static IList create(final IType contentType) { return create(contentType, DEFAULT_SIZE); } @@ -330,7 +499,7 @@ public static IList create() { * @param wrapped * @return */ - public static IList wrap(final IType contentType, final List wrapped) { + public static IList wrap(final IType contentType, final List wrapped) { // return createWithoutCasting(contentType, wrapped); return new GamaListWrapper(wrapped, contentType); } @@ -344,7 +513,7 @@ public static IList wrap(final IType contentType, final List wrappe * @param wrapped * @return */ - public static IList wrap(final IType contentType, final E... wrapped) { + public static IList wrap(final IType contentType, final E... wrapped) { // return createWithoutCasting(contentType, wrapped); return new GamaListArrayWrapper(wrapped, contentType); } @@ -360,16 +529,23 @@ public static IList wrap(final IType contentType, final E... wrapped) * @param wrapped * @return */ - public static IList wrap(final IType contentType, final Collection wrapped) { + public static IList wrap(final IType contentType, final Collection wrapped) { return new GamaListCollectionWrapper(wrapped, contentType); } + /** + * Equals. + * + * @param one + * the one + * @param two + * the two + * @return true, if successful + */ public static boolean equals(final IList one, final IList two) { final Iterator it1 = one.iterator(); final Iterator it2 = two.iterator(); - while (it1.hasNext() && it2.hasNext()) { - if (!Objects.equals(it1.next(), it2.next())) return false; - } + while (it1.hasNext() && it2.hasNext()) { if (!Objects.equals(it1.next(), it2.next())) return false; } return !it1.hasNext() && !it2.hasNext(); } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java b/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java index 4802f085a9..78c79376ca 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaCSVFile.java @@ -3,7 +3,7 @@ * GamaCSVFile.java, in msi.gama.core, is part of the source code of the * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -12,7 +12,6 @@ import static org.apache.commons.lang.StringUtils.splitByWholeSeparatorPreserveAllTokens; -import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; @@ -63,31 +62,34 @@ public static class CSVInfo extends GamaFileMetaData { /** The cols. */ public int cols; - + /** The rows. */ public int rows; - + /** The header. */ public boolean header; - + /** The delimiter. */ public Character delimiter; - - /** The qualifier. */ - public Character qualifier; - + // + // /** The qualifier. */ + // public Character qualifier; + /** The type. */ public final IType type; - + /** The headers. */ public String[] headers; /** * Instantiates a new CSV info. * - * @param fileName the file name - * @param modificationStamp the modification stamp - * @param CSVsep the CS vsep + * @param fileName + * the file name + * @param modificationStamp + * the modification stamp + * @param CSVsep + * the CS vsep */ public CSVInfo(final String fileName, final long modificationStamp, final String CSVsep) { super(modificationStamp); @@ -103,7 +105,8 @@ public CSVInfo(final String fileName, final long modificationStamp, final String /** * Instantiates a new CSV info. * - * @param propertyString the property string + * @param propertyString + * the property string */ public CSVInfo(final String propertyString) { super(propertyString); @@ -171,22 +174,22 @@ public void setHeaders(final String[] newHeaders) { /** The csv separator. */ String csvSeparator = null; - + /** The text qualifier. */ Character textQualifier = null; - + /** The contents type. */ IType contentsType; - + /** The user size. */ GamaPoint userSize; - + /** The has header. */ Boolean hasHeader; - + /** The headers. */ IList headers; - + /** The info. */ CSVInfo info; @@ -207,9 +210,12 @@ public GamaCSVFile(final IScope scope, final String pathName) throws GamaRuntime /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param withHeader the with header + * @param scope + * the scope + * @param pathName + * the path name + * @param withHeader + * the with header */ @doc ( value = "This file constructor allows to read a CSV file with the default separator (coma), with specifying if the model has a header or not (boolean), and no assumption on the type of data. No text qualifier will be used", @@ -224,9 +230,12 @@ public GamaCSVFile(final IScope scope, final String pathName, final Boolean with /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param separator the separator + * @param scope + * the scope + * @param pathName + * the path name + * @param separator + * the separator */ @doc ( value = "This file constructor allows to read a CSV file and specify the separator used, without making any assumption on the type of data. Headers should be detected automatically if they exist. No text qualifier will be used", @@ -240,10 +249,14 @@ public GamaCSVFile(final IScope scope, final String pathName, final String separ /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param separator the separator - * @param withHeader the with header + * @param scope + * the scope + * @param pathName + * the path name + * @param separator + * the separator + * @param withHeader + * the with header */ @doc ( value = "This file constructor allows to read a CSV file and specify (1) the separator used; (2) if the model has a header or not, without making any assumption on the type of data. No text qualifier will be used", @@ -258,11 +271,16 @@ public GamaCSVFile(final IScope scope, final String pathName, final String separ /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param separator the separator - * @param qualifier the qualifier - * @param withHeader the with header + * @param scope + * the scope + * @param pathName + * the path name + * @param separator + * the separator + * @param qualifier + * the qualifier + * @param withHeader + * the with header */ @doc ( value = "This file constructor allows to read a CSV file and specify (1) the separator used; (2) the text qualifier used; (3) if the model has a header or not, without making any assumption on the type of data", @@ -279,10 +297,14 @@ public GamaCSVFile(final IScope scope, final String pathName, final String separ /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param separator the separator - * @param type the type + * @param scope + * the scope + * @param pathName + * the path name + * @param separator + * the separator + * @param type + * the type */ @doc ( value = "This file constructor allows to read a CSV file with a given separator, no header, and the type of data. No text qualifier will be used", @@ -296,11 +318,16 @@ public GamaCSVFile(final IScope scope, final String pathName, final String separ /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param separator the separator - * @param qualifier the qualifier - * @param type the type + * @param scope + * the scope + * @param pathName + * the path name + * @param separator + * the separator + * @param qualifier + * the qualifier + * @param type + * the type */ @doc ( value = "This file constructor allows to read a CSV file and specify the separator, text qualifier to use, and the type of data to read. Headers should be detected automatically if they exist. ", @@ -316,11 +343,16 @@ public GamaCSVFile(final IScope scope, final String pathName, final String separ /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param separator the separator - * @param type the type - * @param withHeader the with header + * @param scope + * the scope + * @param pathName + * the path name + * @param separator + * the separator + * @param type + * the type + * @param withHeader + * the with header */ @doc ( value = "This file constructor allows to read a CSV file with a given separator, the type of data, with specifying if the model has a header or not (boolean). No text qualifier will be used", @@ -336,11 +368,16 @@ public GamaCSVFile(final IScope scope, final String pathName, final String separ /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param separator the separator - * @param type the type - * @param size the size + * @param scope + * the scope + * @param pathName + * the path name + * @param separator + * the separator + * @param type + * the type + * @param size + * the size */ @doc ( value = "This file constructor allows to read a CSV file with a given separator, the type of data, with specifying the number of cols and rows taken into account. No text qualifier will be used", @@ -358,9 +395,12 @@ public GamaCSVFile(final IScope scope, final String pathName, final String separ /** * Instantiates a new gama CSV file. * - * @param scope the scope - * @param pathName the path name - * @param matrix the matrix + * @param scope + * the scope + * @param pathName + * the path name + * @param matrix + * the matrix */ @doc ( value = "This file constructor allows to store a matrix in a CSV file (it does not save it - just store it in memory),", @@ -379,7 +419,8 @@ public GamaCSVFile(final IScope scope, final String pathName, final IMatrix getAttributes(final IScope scope) { /** * Gets the info. * - * @param scope the scope - * @param CSVSep the CSV sep + * @param scope + * the scope + * @param CSVSep + * the CSV sep * @return the info */ private CSVInfo getInfo(final IScope scope, final String CSVSep) { @@ -485,10 +528,13 @@ public IContainerType getGamlType() { /** * Creates the matrix from. * - * @param scope the scope - * @param reader the reader + * @param scope + * the scope + * @param reader + * the reader * @return the i matrix - * @throws IOException Signals that an I/O exception has occurred. + * @throws IOException + * Signals that an I/O exception has occurred. */ private IMatrix createMatrixFrom(final IScope scope, final CsvReader reader) throws IOException { final int t = contentsType.id(); diff --git a/msi.gama.core/src/msi/gama/util/file/GamaDXFFile.java b/msi.gama.core/src/msi/gama/util/file/GamaDXFFile.java index 6b8cbbcbfb..e6c27e9c98 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaDXFFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaDXFFile.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaDXFFile.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * GamaDXFFile.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -16,6 +16,9 @@ import java.util.Iterator; import java.util.List; +import org.locationtech.jts.geom.Envelope; + +import msi.gama.common.geometry.Envelope3D; import msi.gama.ext.kabeja.dxf.DXFArc; import msi.gama.ext.kabeja.dxf.DXFBlock; import msi.gama.ext.kabeja.dxf.DXFCircle; @@ -29,12 +32,7 @@ import msi.gama.ext.kabeja.parser.DXFParser; import msi.gama.ext.kabeja.parser.Parser; import msi.gama.ext.kabeja.parser.ParserBuilder; - -import org.locationtech.jts.geom.Envelope; - -import msi.gama.common.geometry.Envelope3D; import msi.gama.metamodel.shape.GamaPoint; - import msi.gama.metamodel.shape.IShape; import msi.gama.precompiler.GamlAnnotations.doc; import msi.gama.precompiler.GamlAnnotations.example; @@ -68,14 +66,28 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaDXFFile extends GamaGeometryFile { + /** The size. */ GamaPoint size; + + /** The unit. */ Double unit; + + /** The x t. */ double x_t; + + /** The y t. */ double y_t; - protected static final double QUARTER_CIRCLE_ANGLE = Math.tan(0.39269908169872414D); - - + /** The Constant QUARTER_CIRCLE_ANGLE. */ + protected static final double QUARTER_CIRCLE_ANGLE = Math.tan(0.39269908169872414D); + + /** + * Instantiates a new gama DXF file. + * + * @param scope the scope + * @param pathName the path name + * @throws GamaRuntimeException the gama runtime exception + */ @doc ( value = "This file constructor allows to read a dxf (.dxf) file", examples = { @example ( @@ -85,6 +97,14 @@ public GamaDXFFile(final IScope scope, final String pathName) throws GamaRuntime super(scope, pathName); } + /** + * Instantiates a new gama DXF file. + * + * @param scope the scope + * @param pathName the path name + * @param unit the unit + * @throws GamaRuntimeException the gama runtime exception + */ @doc ( value = "This file constructor allows to read a dxf (.dxf) file and specify the unit (meter by default)", examples = { @example ( @@ -92,9 +112,7 @@ public GamaDXFFile(final IScope scope, final String pathName) throws GamaRuntime isExecutable = false) }) public GamaDXFFile(final IScope scope, final String pathName, final Double unit) throws GamaRuntimeException { super(scope, pathName); - if (unit <= 0) { - GamaRuntimeException.error("the unity given has to be higher than 0", scope); - } + if (unit <= 0) { GamaRuntimeException.error("the unity given has to be higher than 0", scope); } this.unit = unit; } @@ -109,37 +127,66 @@ public IList getAttributes(final IScope scope) { return GamaListFactory.EMPTY_LIST; } + /** + * Creates the polyline. + * + * @param scope the scope + * @param pts the pts + * @return the i shape + */ public IShape createPolyline(final IScope scope, final IList pts) { - if (pts.isEmpty()) { return null; } + if (pts.isEmpty()) return null; final IShape shape = GamaGeometryType.buildPolyline(pts); if (shape != null) { - if (size != null) { return Spatial.Transformations.scaled_to(scope, shape, size); } + if (size != null) return Spatial.Transformations.scaled_to(scope, shape, size); return shape; } return null; } + /** + * Creates the polygon. + * + * @param scope the scope + * @param pts the pts + * @return the i shape + */ public IShape createPolygon(final IScope scope, final IList pts) { - if (pts.isEmpty()) { return null; } + if (pts.isEmpty()) return null; final IShape shape = GamaGeometryType.buildPolygon(pts); if (shape != null) { - if (size != null) { return Spatial.Transformations.scaled_to(scope, shape, size); } + if (size != null) return Spatial.Transformations.scaled_to(scope, shape, size); return shape; } return null; } + /** + * Creates the circle. + * + * @param scope the scope + * @param location the location + * @param radius the radius + * @return the i shape + */ public IShape createCircle(final IScope scope, final GamaPoint location, final double radius) { IShape shape = GamaGeometryType.buildCircle(radius, location).getExteriorRing(scope); if (shape != null) { - if (size != null) { return Spatial.Transformations.scaled_to(scope, shape, size); } + if (size != null) return Spatial.Transformations.scaled_to(scope, shape, size); return shape; } return null; } + /** + * Manage obj. + * + * @param scope the scope + * @param obj the obj + * @return the i shape + */ public IShape manageObj(final IScope scope, final DXFSolid obj) { - if (obj == null) { return null; } + if (obj == null) return null; final IList list = GamaListFactory.create(Types.POINT); list.add(new GamaPoint(obj.getPoint1().getX() * (unit == null ? 1 : unit) - x_t, obj.getPoint1().getY() * (unit == null ? 1 : unit) - y_t, @@ -154,21 +201,33 @@ public IShape manageObj(final IScope scope, final DXFSolid obj) { obj.getPoint4().getY() * (unit == null ? 1 : unit) - y_t, obj.getPoint4().getZ() * (unit == null ? 1 : unit))); - final IShape shape = createPolygon(scope, list); - - return shape; + return createPolygon(scope, list); } + /** + * Manage obj. + * + * @param scope the scope + * @param obj the obj + * @return the i shape + */ public IShape manageObj(final IScope scope, final DXFCircle obj) { - if (obj == null) { return null; } + if (obj == null) return null; final GamaPoint pt = new GamaPoint(obj.getCenterPoint().getX() * (unit == null ? 1 : unit) - x_t, obj.getCenterPoint().getY() * (unit == null ? 1 : unit) - y_t, obj.getCenterPoint().getZ() * (unit == null ? 1 : unit)); return createCircle(scope, pt, obj.getRadius() * (unit == null ? 1 : unit)); } + /** + * Manage obj. + * + * @param scope the scope + * @param obj the obj + * @return the i shape + */ public IShape manageObj(final IScope scope, final DXFLine obj) { - if (obj == null) { return null; } + if (obj == null) return null; final IList list = GamaListFactory.create(Types.POINT); list.add(new GamaPoint(obj.getStartPoint().getX() * (unit == null ? 1 : unit) - x_t, obj.getStartPoint().getY() * (unit == null ? 1 : unit) - y_t, @@ -178,11 +237,16 @@ public IShape manageObj(final IScope scope, final DXFLine obj) { obj.getEndPoint().getZ() * (unit == null ? 1 : unit))); return createPolyline(scope, list); } - - + /** + * Manage obj. + * + * @param scope the scope + * @param obj the obj + * @return the i shape + */ public IShape manageObj(final IScope scope, final DXFArc obj) { - if (obj == null) { return null; } + if (obj == null) return null; final IList list = GamaListFactory.create(Types.POINT); list.add(new GamaPoint(obj.getStartPoint().getX() * (unit == null ? 1 : unit) - x_t, obj.getStartPoint().getY() * (unit == null ? 1 : unit) - y_t, @@ -192,113 +256,148 @@ public IShape manageObj(final IScope scope, final DXFArc obj) { obj.getEndPoint().getZ() * (unit == null ? 1 : unit))); return createPolyline(scope, list); } - - - public GamaPoint toGamaPoint(DXFVertex v) { - return new GamaPoint(v.getPoint().getX(),v.getPoint().getY(),v.getPoint().getZ()); + + /** + * To gama point. + * + * @param v the v + * @return the gama point + */ + public GamaPoint toGamaPoint(final DXFVertex v) { + return new GamaPoint(v.getPoint().getX(), v.getPoint().getY(), v.getPoint().getZ()); } - - protected void addToLists(IScope scope, DXFPolyline pline, DXFVertex start, DXFVertex end, IList list) { + + /** + * Adds the to lists. + * + * @param scope the scope + * @param pline the pline + * @param start the start + * @param end the end + * @param list the list + */ + protected void addToLists(final IScope scope, final DXFPolyline pline, final DXFVertex start, final DXFVertex end, + final IList list) { IList locs = GamaListFactory.create(Types.POINT); locs.add(new GamaPoint(start.getPoint().getX(), start.getPoint().getY(), start.getPoint().getZ())); - // calculte the height - GamaPoint startPt = toGamaPoint(start); - GamaPoint endPt = toGamaPoint(end); - if (start.getBulge() == 0) { - list.add(startPt); - list.add(endPt); - - } else { - double l = startPt.distance(endPt); - - double s = start.getBulge() * l / 2; - - IShape c = Creation.EllipticalArc(scope,startPt, endPt, s,20); - list.addAll(c.getPoints()); - } - - } - - public IList getPoints(IScope scope, final DXFPolyline obj) { - IList list = GamaListFactory.create(Types.POINT); - - Iterator i = obj.getVertexIterator(); - - if (i.hasNext()) { - DXFVertex last; - DXFVertex first; - DXFVertex v = null; - - last = first = (DXFVertex) i.next(); - list.add(new GamaPoint(last.getPoint().getX(),last.getPoint().getY(),last.getPoint().getZ())); - - while (i.hasNext()) { - v = (DXFVertex) i.next(); - addToLists(scope,obj,last, v, list); - last = v; - } - - if ((v != null) && (v.getBulge() != 0.0)) { - addToLists(scope,obj,v, first, list); - } - - } - - boolean change = true; - while (change) { - change = false; - for (int k = 0; k < list.size() - 1; k ++) { - GamaPoint pt1 = (GamaPoint)list.get(k); - GamaPoint pt2 = (GamaPoint)list.get(k+1); - if (pt1.euclidianDistanceTo(pt2) < 0.000001) { - list.remove(k+1); - change = true; - break; - } - } - } - - return list; - } - public IShape manageObj(final IScope scope, final DXFPolyline obj) { - if (obj == null) { return null; } - IList list_ = getPoints(scope,obj); - - final GamaPoint pt = (GamaPoint) list_.get(list_.size() - 1); - if (pt.getX() == 0 && pt.getY() == 0 && pt.getZ() == 0) { - list_.remove(pt); + // calculte the height + GamaPoint startPt = toGamaPoint(start); + GamaPoint endPt = toGamaPoint(end); + if (start.getBulge() == 0) { + list.add(startPt); + list.add(endPt); + + } else { + double l = startPt.distance(endPt); + + double s = start.getBulge() * l / 2; + + IShape c = Creation.EllipticalArc(scope, startPt, endPt, s, 20); + list.addAll(c.getPoints()); } - - + + } + + /** + * Gets the points. + * + * @param scope the scope + * @param obj the obj + * @return the points + */ + public IList getPoints(final IScope scope, final DXFPolyline obj) { + IList list = GamaListFactory.create(Types.POINT); + + Iterator i = obj.getVertexIterator(); + + if (i.hasNext()) { + DXFVertex last; + DXFVertex first; + DXFVertex v = null; + + last = first = (DXFVertex) i.next(); + list.add(new GamaPoint(last.getPoint().getX(), last.getPoint().getY(), last.getPoint().getZ())); + + while (i.hasNext()) { + v = (DXFVertex) i.next(); + addToLists(scope, obj, last, v, list); + last = v; + } + + if (v != null && v.getBulge() != 0.0) { addToLists(scope, obj, v, first, list); } + + } + + boolean change = true; + while (change) { + change = false; + for (int k = 0; k < list.size() - 1; k++) { + GamaPoint pt1 = (GamaPoint) list.get(k); + GamaPoint pt2 = (GamaPoint) list.get(k + 1); + if (pt1.euclidianDistanceTo(pt2) < 0.000001) { + list.remove(k + 1); + change = true; + break; + } + } + } + + return list; + } + + /** + * Manage obj. + * + * @param scope the scope + * @param obj the obj + * @return the i shape + */ + public IShape manageObj(final IScope scope, final DXFPolyline obj) { + if (obj == null) return null; + IList list_ = getPoints(scope, obj); + + final GamaPoint pt = list_.get(list_.size() - 1); + if (pt.getX() == 0 && pt.getY() == 0 && pt.getZ() == 0) { list_.remove(pt); } + IList list = GamaListFactory.create(Types.POINT); - - + for (GamaPoint p : list_) { list.add(new GamaPoint(p.getX() * (unit == null ? 1 : unit) - x_t, p.getY() * (unit == null ? 1 : unit) - y_t, p.getZ() * (unit == null ? 1 : unit))); } - - if (list.size() < 2) { return null; } - if (obj.isClosed() && (list.get(0) != list.get(list.size() - 1))) { - list.add(list.firstValue(scope)); - } + + if (list.size() < 2) return null; + if (obj.isClosed() && list.get(0) != list.get(list.size() - 1)) { list.add(list.firstValue(scope)); } return createPolyline(scope, list); } + /** + * Define geom. + * + * @param scope the scope + * @param obj the obj + * @return the i shape + */ public IShape defineGeom(final IScope scope, final Object obj) { if (obj != null) { - if (obj instanceof DXFArc) { return manageObj(scope, (DXFArc) obj); } - if (obj instanceof DXFLine) { return manageObj(scope, (DXFLine) obj); } - if (obj instanceof DXFPolyline) { return manageObj(scope, (DXFPolyline) obj); } - if (obj instanceof DXFSolid) { return manageObj(scope, (DXFSolid) obj); } - if (obj instanceof DXFCircle) { return manageObj(scope, (DXFCircle) obj); } - + if (obj instanceof DXFArc) return manageObj(scope, (DXFArc) obj); + if (obj instanceof DXFLine) return manageObj(scope, (DXFLine) obj); + if (obj instanceof DXFPolyline) return manageObj(scope, (DXFPolyline) obj); + if (obj instanceof DXFSolid) return manageObj(scope, (DXFSolid) obj); + if (obj instanceof DXFCircle) return manageObj(scope, (DXFCircle) obj); + } - + return null; } + /** + * Fill buffer. + * + * @param scope the scope + * @param doc the doc + */ protected void fillBuffer(final IScope scope, final DXFDocument doc) { final IList geoms = GamaListFactory.create(Types.GEOMETRY); final double xmax = (doc.getBounds().getMaximumX() - doc.getBounds().getMinimumX()) * (unit == null ? 1 : unit); @@ -317,9 +416,7 @@ protected void fillBuffer(final IScope scope, final DXFDocument doc) { for (final DXFEntity obj : entity_list) { final IShape g = defineGeom(scope, obj); if (g != null && g.intersects(env)) { - if (entities.contains(g)) { - continue; - } + if (entities.contains(g)) { continue; } entities.add(g); g.setAttribute("layer", obj.getLayerName()); @@ -334,9 +431,7 @@ protected void fillBuffer(final IScope scope, final DXFDocument doc) { g.setAttribute("color", new GamaColor(obj.getColorRGB()[0], obj.getColorRGB()[1], obj.getColorRGB()[2], 255)); } - if (obj.getLineType() != null) { - g.setAttribute("line_type", obj.getLineType()); - } + if (obj.getLineType() != null) { g.setAttribute("line_type", obj.getLineType()); } geoms.add(g); } @@ -353,9 +448,7 @@ protected void fillBuffer(final IScope scope, final DXFDocument doc) { final DXFEntity obj = (DXFEntity) itent.next(); final IShape g = defineGeom(scope, obj); if (g != null && g.intersects(env)) { - if (entities.contains(g)) { - continue; - } + if (entities.contains(g)) { continue; } entities.add(g); g.setAttribute("layer", obj.getLayerName()); @@ -371,9 +464,7 @@ protected void fillBuffer(final IScope scope, final DXFDocument doc) { g.setAttribute("color", new GamaColor(obj.getColorRGB()[0], obj.getColorRGB()[1], obj.getColorRGB()[2], 255)); } - if (obj.getLineType() != null) { - g.setAttribute("line_type", obj.getLineType()); - } + if (obj.getLineType() != null) { g.setAttribute("line_type", obj.getLineType()); } geoms.add(g); } @@ -385,7 +476,7 @@ protected void fillBuffer(final IScope scope, final DXFDocument doc) { @Override protected void fillBuffer(final IScope scope) throws GamaRuntimeException { - if (getBuffer() != null) { return; } + if (getBuffer() != null) return; final Parser parser = ParserBuilder.createDefaultParser(); try (InputStream in = new FileInputStream(getFile(scope))) { parser.parse(in, DXFParser.DEFAULT_ENCODING); @@ -411,11 +502,9 @@ public Envelope3D computeEnvelope(final IScope scope) { // get the documnet and the layer final DXFDocument doc = parser.getDocument(); - final Envelope3D env = Envelope3D.of(new Envelope(0, + return Envelope3D.of(new Envelope(0, (doc.getBounds().getMaximumX() - doc.getBounds().getMinimumX()) * (unit == null ? 1 : unit), 0, (doc.getBounds().getMaximumY() - doc.getBounds().getMinimumY()) * (unit == null ? 1 : unit))); - - return env; } catch (final Exception e) { e.printStackTrace(); diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphDimacs.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphDimacs.java index 98d86feba4..986b9be352 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphDimacs.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphDimacs.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphMLFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphDimacs.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -18,6 +18,9 @@ import msi.gaml.species.ISpecies; import msi.gaml.types.IType; +/** + * The Class GamaGraphDimacs. + */ @file ( name = "graphdimacs", extensions = { "dimacs" }, @@ -26,23 +29,46 @@ doc = @doc ("Represents files that contain Graph information. The internal representation is a graph")) @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGraphDimacs extends GamaGraphFile { - + + /** + * Instantiates a new gama graph dimacs. + * + * @param scope the scope + * @param pn the pn + * @throws GamaRuntimeException the gama runtime exception + */ + @doc ("References a dimacs file by its filename") public GamaGraphDimacs(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } + /** + * Instantiates a new gama graph dimacs. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + */ + @doc ("References a dimacs file by its filename and the species to use to instantiate the nodes") public GamaGraphDimacs(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName, nodeSpecies); } - public GamaGraphDimacs(final IScope scope, final String pathName, final ISpecies nodeSpecies, final ISpecies edgeSpecies) { - super(scope, pathName,nodeSpecies,edgeSpecies); + /** + * Instantiates a new gama graph dimacs. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + * @param edgeSpecies the edge species + */ + @doc ("References a dimacs file by its filename and the species to use to instantiate the nodes and the edges") + public GamaGraphDimacs(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { + super(scope, pathName, nodeSpecies, edgeSpecies); } - @Override - protected String getFileType() { - return "dimacs"; - } + protected String getFileType() { return "dimacs"; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphDotFile.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphDotFile.java index 68621d2376..30f9e3e864 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphDotFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphDotFile.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphMLFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphDotFile.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -18,6 +18,9 @@ import msi.gaml.species.ISpecies; import msi.gaml.types.IType; +/** + * The Class GamaGraphDotFile. + */ @file ( name = "graphdot", extensions = { "dot" }, @@ -27,22 +30,55 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGraphDotFile extends GamaGraphFile { + /** + * Instantiates a new gama graph dot file. + * + * @param scope + * the scope + * @param pn + * the pn + * @throws GamaRuntimeException + * the gama runtime exception + */ + @doc ("References a dot graph file by its filename") public GamaGraphDotFile(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } - + /** + * Instantiates a new gama graph dot file. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + */ + @doc ("References a dot graph file by its filename and the species to use to instantiate the nodes") public GamaGraphDotFile(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName, nodeSpecies); } - public GamaGraphDotFile(final IScope scope, final String pathName,final ISpecies nodeSpecies, final ISpecies edgeSpecies) { - super(scope, pathName,nodeSpecies,edgeSpecies); + /** + * Instantiates a new gama graph dot file. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + * @param edgeSpecies + * the edge species + */ + @doc ("References a dot graph file by its filename and the 2 species to use to instantiate the nodes and the edges") + public GamaGraphDotFile(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { + super(scope, pathName, nodeSpecies, edgeSpecies); } - + @Override - protected String getFileType() { - return "dot"; - } + protected String getFileType() { return "dot"; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphFile.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphFile.java index 512c9b37a4..ad8146b0bf 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphFile.java @@ -1,16 +1,15 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphFile.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * ********************************************************************************************************/ package msi.gama.util.file; - import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DirectedMultigraph; import org.jgrapht.nio.GraphImporter; @@ -26,21 +25,50 @@ import msi.gaml.types.IContainerType; import msi.gaml.types.Types; +/** + * The Class GamaGraphFile. + */ public abstract class GamaGraphFile extends GamaFile, Object> { + + /** The node S. */ ISpecies nodeS = null; - ISpecies edgeS = null; + /** The edge S. */ + ISpecies edgeS = null; + + /** + * Instantiates a new gama graph file. + * + * @param scope the scope + * @param pn the pn + * @throws GamaRuntimeException the gama runtime exception + */ public GamaGraphFile(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } - + /** + * Instantiates a new gama graph file. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + */ public GamaGraphFile(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName); nodeS = nodeSpecies; } - public GamaGraphFile(final IScope scope, final String pathName,final ISpecies nodeSpecies, final ISpecies edgeSpecies) { + /** + * Instantiates a new gama graph file. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + * @param edgeSpecies the edge species + */ + public GamaGraphFile(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { super(scope, pathName); nodeS = nodeSpecies; edgeS = edgeSpecies; @@ -50,23 +78,26 @@ public GamaGraphFile(final IScope scope, final String pathName,final ISpecies no public Envelope3D computeEnvelope(final IScope scope) { return null; } - + @Override protected void fillBuffer(final IScope scope) throws GamaRuntimeException { - if (getBuffer() != null) { return; } - GraphImporter parser = GraphImporters.getGraphImporter(getFileType()); - DirectedMultigraph graph = new DirectedMultigraph<>( - SupplierUtil.createStringSupplier(), SupplierUtil.DEFAULT_EDGE_SUPPLIER, true); - + if (getBuffer() != null) return; + GraphImporter parser = GraphImporters.getGraphImporter(getFileType()); + DirectedMultigraph graph = + new DirectedMultigraph<>(SupplierUtil.createStringSupplier(), SupplierUtil.DEFAULT_EDGE_SUPPLIER, true); + parser.importGraph(graph, this.getFile(scope)); setBuffer(new GamaGraph<>(scope, graph, nodeS, edgeS)); } - - abstract protected String getFileType() ; + + /** + * Gets the file type. + * + * @return the file type + */ + abstract protected String getFileType(); @Override - public IContainerType getGamlType() { - return Types.GRAPH; - } + public IContainerType getGamlType() { return Types.GRAPH; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphGML.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphGML.java index 5a92fbfd70..06c1d422f4 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphGML.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphGML.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphMLFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphGML.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -18,6 +18,9 @@ import msi.gaml.species.ISpecies; import msi.gaml.types.IType; +/** + * The Class GamaGraphGML. + */ @file ( name = "graphgml", extensions = { "gml" }, @@ -27,21 +30,55 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGraphGML extends GamaGraphFile { + /** + * Instantiates a new gama graph GML. + * + * @param scope + * the scope + * @param pn + * the pn + * @throws GamaRuntimeException + * the gama runtime exception + */ + @doc ("References a gml graph file by its filename") public GamaGraphGML(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } + /** + * Instantiates a new gama graph GML. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + */ + @doc ("References a gml graph file by its filename and the species to use to instantiate the nodes") public GamaGraphGML(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName, nodeSpecies); } - public GamaGraphGML(final IScope scope, final String pathName, final ISpecies nodeSpecies, final ISpecies edgeSpecies) { - super(scope, pathName,nodeSpecies,edgeSpecies); + /** + * Instantiates a new gama graph GML. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + * @param edgeSpecies + * the edge species + */ + @doc ("References a gml graph file by its filename and the 2 species to use to instantiate the nodes and the edges") + public GamaGraphGML(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { + super(scope, pathName, nodeSpecies, edgeSpecies); } @Override - protected String getFileType() { - return "gml"; - } + protected String getFileType() { return "gml"; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphGexf.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphGexf.java index 1dbe257f16..e247f52d57 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphGexf.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphGexf.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphMLFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphGexf.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -18,6 +18,9 @@ import msi.gaml.species.ISpecies; import msi.gaml.types.IType; +/** + * The Class GamaGraphGexf. + */ @file ( name = "graphgexf", extensions = { "gexf" }, @@ -27,21 +30,55 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGraphGexf extends GamaGraphFile { + /** + * Instantiates a new gama graph gexf. + * + * @param scope + * the scope + * @param pn + * the pn + * @throws GamaRuntimeException + * the gama runtime exception + */ + @doc ("References a gexf graph file by its filename") public GamaGraphGexf(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } + /** + * Instantiates a new gama graph gexf. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + */ + @doc ("References a gexf graph file by its filename and the species to use to instantiate the nodes") public GamaGraphGexf(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName, nodeSpecies); } - public GamaGraphGexf(final IScope scope, final String pathName, final ISpecies nodeSpecies, final ISpecies edgeSpecies) { - super(scope, pathName,nodeSpecies,edgeSpecies); + /** + * Instantiates a new gama graph gexf. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + * @param edgeSpecies + * the edge species + */ + @doc ("References a gexf graph file by its filename and the 2 species to use to instantiate the nodes and the edges") + public GamaGraphGexf(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { + super(scope, pathName, nodeSpecies, edgeSpecies); } @Override - protected String getFileType() { - return "gexf"; - } + protected String getFileType() { return "gexf"; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphGraph6.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphGraph6.java index 73bb6af7cb..c3da1477d1 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphGraph6.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphGraph6.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphMLFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphGraph6.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -18,6 +18,9 @@ import msi.gaml.species.ISpecies; import msi.gaml.types.IType; +/** + * The Class GamaGraphGraph6. + */ @file ( name = "graph6", extensions = { "graph6" }, @@ -27,21 +30,55 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGraphGraph6 extends GamaGraphFile { + /** + * Instantiates a new gama graph graph 6. + * + * @param scope + * the scope + * @param pn + * the pn + * @throws GamaRuntimeException + * the gama runtime exception + */ + @doc ("References a graph6 file by its filename") public GamaGraphGraph6(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } + /** + * Instantiates a new gama graph graph 6. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + */ + @doc ("References a graph6 file by its filename and the species to use to instantiate the nodes") public GamaGraphGraph6(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName, nodeSpecies); } - public GamaGraphGraph6(final IScope scope, final String pathName,final ISpecies nodeSpecies, final ISpecies edgeSpecies) { - super(scope, pathName,nodeSpecies,edgeSpecies); + /** + * Instantiates a new gama graph graph 6. + * + * @param scope + * the scope + * @param pathName + * the path name + * @param nodeSpecies + * the node species + * @param edgeSpecies + * the edge species + */ + @doc ("References a graph6 file by its filename and the species to use to instantiate the nodes and the edges") + public GamaGraphGraph6(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { + super(scope, pathName, nodeSpecies, edgeSpecies); } @Override - protected String getFileType() { - return "graph6"; - } + protected String getFileType() { return "graph6"; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphMLFile.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphMLFile.java index 4167c85357..e0a75840cc 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphMLFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphMLFile.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphMLFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphMLFile.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -18,6 +18,9 @@ import msi.gaml.species.ISpecies; import msi.gaml.types.IType; +/** + * The Class GamaGraphMLFile. + */ @file ( name = "graphml", extensions = { "graphml" }, @@ -26,22 +29,46 @@ doc = @doc ("Represents files that contain Graph information. The internal representation is a graph")) @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGraphMLFile extends GamaGraphFile { - + + /** + * Instantiates a new gama graph ML file. + * + * @param scope the scope + * @param pn the pn + * @throws GamaRuntimeException the gama runtime exception + */ + @doc ("References a graphml graph file by its filename") public GamaGraphMLFile(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } + /** + * Instantiates a new gama graph ML file. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + */ + @doc ("References a graphml graph file by its filename and the species to use to instantiate the nodes") public GamaGraphMLFile(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName, nodeSpecies); } - public GamaGraphMLFile(final IScope scope, final String pathName, final ISpecies nodeSpecies, final ISpecies edgeSpecies) { - super(scope, pathName,nodeSpecies,edgeSpecies); + /** + * Instantiates a new gama graph ML file. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + * @param edgeSpecies the edge species + */ + @doc ("References a graphml graph file by its filename and the 2 species to use to instantiate the nodes and the edges") + public GamaGraphMLFile(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { + super(scope, pathName, nodeSpecies, edgeSpecies); } @Override - protected String getFileType() { - return "graphml"; - } + protected String getFileType() { return "graphml"; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGraphTsplib.java b/msi.gama.core/src/msi/gama/util/file/GamaGraphTsplib.java index 75776bb73b..4fc74cb667 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGraphTsplib.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGraphTsplib.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.util.file.GamaGraphMLFile.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaGraphTsplib.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -18,6 +18,9 @@ import msi.gaml.species.ISpecies; import msi.gaml.types.IType; +/** + * The Class GamaGraphTsplib. + */ @file ( name = "graphtsplib", extensions = { "tsplib" }, @@ -27,21 +30,45 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGraphTsplib extends GamaGraphFile { + /** + * Instantiates a new gama graph tsplib. + * + * @param scope the scope + * @param pn the pn + * @throws GamaRuntimeException the gama runtime exception + */ + @doc ("References a tsplib graph file by its filename") public GamaGraphTsplib(final IScope scope, final String pn) throws GamaRuntimeException { super(scope, pn); } + /** + * Instantiates a new gama graph tsplib. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + */ + @doc ("References a tsplib graph file by its filename and the species to use to instantiate the nodes") public GamaGraphTsplib(final IScope scope, final String pathName, final ISpecies nodeSpecies) { super(scope, pathName, nodeSpecies); } - public GamaGraphTsplib(final IScope scope, final String pathName, final ISpecies nodeSpecies, final ISpecies edgeSpecies) { - super(scope, pathName,nodeSpecies,edgeSpecies); + /** + * Instantiates a new gama graph tsplib. + * + * @param scope the scope + * @param pathName the path name + * @param nodeSpecies the node species + * @param edgeSpecies the edge species + */ + @doc ("References a tsplib graph file by its filename and the 2 species to use to instantiate the nodes and the edges") + public GamaGraphTsplib(final IScope scope, final String pathName, final ISpecies nodeSpecies, + final ISpecies edgeSpecies) { + super(scope, pathName, nodeSpecies, edgeSpecies); } @Override - protected String getFileType() { - return "tsplib"; - } + protected String getFileType() { return "tsplib"; } } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java b/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java index 4e7b8e1d85..77d5afce8a 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaGridFile.java @@ -3,7 +3,7 @@ * GamaGridFile.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform * (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -277,19 +277,18 @@ private void createCoverage(final IScope scope) { */ private void createCoverage(final IScope scope, final GamaField field) { // temporary fixes #3128 - the code comes from the save statement... maybe we can do better - - //old code - /*double[] data = field.getMatrix(); - - DataBuffer buffer = new DataBufferDouble(data, data.length); - SampleModel sample = new BandedSampleModel(DataBuffer.TYPE_DOUBLE, field.numCols, field.numRows, - field.getBandsNumber(scope)); - WritableRaster raster = Raster.createWritableRaster(sample, buffer, null); - Envelope2D envelope = new Envelope2D(getCRS(scope), 0, 0, scope.getSimulation().getWidth(), - scope.getSimulation().getHeight()); - GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null); - GridCoverage2D cov = factory.create(getName(scope), raster, envelope); - coverage = cov;*/ + + // old code + /* + * double[] data = field.getMatrix(); + * + * DataBuffer buffer = new DataBufferDouble(data, data.length); SampleModel sample = new + * BandedSampleModel(DataBuffer.TYPE_DOUBLE, field.numCols, field.numRows, field.getBandsNumber(scope)); + * WritableRaster raster = Raster.createWritableRaster(sample, buffer, null); Envelope2D envelope = new + * Envelope2D(getCRS(scope), 0, 0, scope.getSimulation().getWidth(), scope.getSimulation().getHeight()); + * GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null); GridCoverage2D cov = + * factory.create(getName(scope), raster, envelope); coverage = cov; + */ final boolean nullProjection = scope.getSimulation().getProjectionFactory().getWorld() == null; final int cols = field.numCols; @@ -301,21 +300,18 @@ private void createCoverage(final IScope scope, final GamaField field) { final float[][] imagePixelData = new float[rows][cols]; for (int row = 0; row < rows; row++) { - for (int col = 0; col < cols; col++) { - imagePixelData[row][col] = field.get(scope, col, row).floatValue(); - } + for (int col = 0; col < cols; col++) { imagePixelData[row][col] = field.get(scope, col, row).floatValue(); } } final double width = scope.getSimulation().getEnvelope().getWidth(); final double height = scope.getSimulation().getEnvelope().getHeight(); Envelope2D refEnvelope; - + refEnvelope = new Envelope2D(this.getCRS(scope), x, y, width, height); - coverage = new GridCoverageFactory().create("data", imagePixelData, refEnvelope); - + } /** @@ -339,15 +335,15 @@ protected CoordinateReferenceSystem getCRS(final IScope scope) { @Override protected void flushBuffer(final IScope scope, final Facets facets) throws GamaRuntimeException { - if (!writable || (coverage == null)) return; + if (!writable || coverage == null) return; try { final File f = getFile(scope); f.setWritable(true); GridCoverageWriter writer; - + if (isTiff(scope)) { final GeoTiffFormat format = new GeoTiffFormat(); - writer = format.getWriter(f); + writer = format.getWriter(f); } else { writer = new ArcGridWriter(f); } @@ -587,11 +583,11 @@ protected CoordinateReferenceSystem getOwnCRS(final IScope scope) { final String sourceAsString; sourceAsString = source.getAbsolutePath(); final int index = sourceAsString.lastIndexOf('.'); - final StringBuffer prjFileName; + final StringBuilder prjFileName; if (index == -1) { - prjFileName = new StringBuffer(sourceAsString); + prjFileName = new StringBuilder(sourceAsString); } else { - prjFileName = new StringBuffer(sourceAsString.substring(0, index)); + prjFileName = new StringBuilder(sourceAsString.substring(0, index)); } prjFileName.append(".prj"); @@ -599,28 +595,14 @@ protected CoordinateReferenceSystem getOwnCRS(final IScope scope) { final File prjFile = new File(prjFileName.toString()); if (prjFile.exists()) { // it exists then we have to read it - PrjFileReader projReader = null; - try (FileInputStream fip = new FileInputStream(prjFile); final FileChannel channel = fip.getChannel();) { - projReader = new PrjFileReader(channel); + try (FileInputStream fip = new FileInputStream(prjFile); + final FileChannel channel = fip.getChannel(); + PrjFileReader projReader = new PrjFileReader(channel);) { return projReader.getCoordinateReferenceSystem(); - } catch (final IOException e) { - // warn about the error but proceed, it is not fatal - // we have at least the default crs to use - return null; - } catch (final FactoryException e) { + } catch (final IOException | FactoryException e) { // warn about the error but proceed, it is not fatal // we have at least the default crs to use return null; - } finally { - if (projReader != null) { - try { - projReader.close(); - } catch (final IOException e) { - // warn about the error but proceed, it is not fatal - // we have at least the default crs to use - return null; - } - } } } if (isTiff(scope)) { @@ -670,7 +652,7 @@ public Double valueOf(final IScope scope, final double x, final double y) { if (getBuffer() == null) { fillBuffer(scope); } Object vals = null; try { - vals = coverage.evaluate(new DirectPosition2D(x, y)); + vals = coverage.evaluate(new DirectPosition2D(x, y)); } catch (final Exception e) { vals = noData.doubleValue(); } diff --git a/msi.gama.core/src/msi/gama/util/file/GamaShapeFile.java b/msi.gama.core/src/msi/gama/util/file/GamaShapeFile.java index a3b6577d16..4a69141a26 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamaShapeFile.java +++ b/msi.gama.core/src/msi/gama/util/file/GamaShapeFile.java @@ -3,7 +3,7 @@ * GamaShapeFile.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform * (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -137,7 +137,7 @@ public ShapeInfo(final IScope scope, final URL url, final long modificationStamp try { env = env.transform(new ProjectionFactory().getTargetCRS(scope), true); } catch (final Exception e) { - if (store != null) { store.dispose(); } + store.dispose(); throw e; } } @@ -145,7 +145,7 @@ public ShapeInfo(final IScope scope, final URL url, final long modificationStamp number = features.size(); } catch (final Exception e) { - if (store != null) { store.dispose(); } + store.dispose(); DEBUG.ERR("Error in loading shapefile: " + e.getMessage()); } final java.util.List att_list = store.getSchema().getAttributeDescriptors(); @@ -479,43 +479,43 @@ protected final void readShapes(final IScope scope) { } catch (final Exception ex) { try { ShpFiles shp = new ShpFiles(getFile(scope).toURI().toURL()); - ShapefileReader reader = new ShapefileReader(shp, false, false, GeometryUtils.GEOMETRY_FACTORY); - reader.setFlatGeometry(true); - // System.out.println("count:" + reader.getCount(0)); - while (reader.hasNext()) { - Record record = reader.nextRecord(); - Geometry g = GeometryUtils.cleanGeometry((Geometry) record.shape()); - - if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) { - - if (!with3D && g.getNumPoints() > 2) { - try { - if (!g.isValid()) { g = GeometryUtils.cleanGeometry(g); } - } catch (Exception e) { - g = GeometryUtils.cleanGeometry(g); + try (ShapefileReader reader = new ShapefileReader(shp, false, false, GeometryUtils.GEOMETRY_FACTORY)) { + reader.setFlatGeometry(true); + // System.out.println("count:" + reader.getCount(0)); + while (reader.hasNext()) { + Record record = reader.nextRecord(); + Geometry g = GeometryUtils.cleanGeometry((Geometry) record.shape()); + + if (g != null && !g.isEmpty() /* Fix for Issue 725 && 677 */ ) { + + if (!with3D && g.getNumPoints() > 2) { + try { + if (!g.isValid()) { g = GeometryUtils.cleanGeometry(g); } + } catch (Exception e) { + g = GeometryUtils.cleanGeometry(g); + } } - } - g = gis.transform(g); - if (!with3D) { - g.apply(ZERO_Z); - g.geometryChanged(); - } - g = multiPolygonManagement(g); + g = gis.transform(g); + if (!with3D) { + g.apply(ZERO_Z); + g.geometryChanged(); + } + g = multiPolygonManagement(g); - for (int i = 0; i < g.getNumGeometries(); i++) { - GamaShape gt = new GamaGisGeometry(g.getGeometryN(i), null); - if (gt.getInnerGeometry() != null) { getBuffer().add(gt); } - } + for (int i = 0; i < g.getNumGeometries(); i++) { + GamaShape gt = new GamaGisGeometry(g.getGeometryN(i), null); + if (gt.getInnerGeometry() != null) { getBuffer().add(gt); } + } - } else if (g == null) { - // See Issue 725 - GAMA.reportError(scope, - GamaRuntimeException.warning( - "geometry could not be added as it is " + "nil: " + record.number, scope), - false); + } else if (g == null) { + // See Issue 725 + GAMA.reportError(scope, + GamaRuntimeException.warning( + "geometry could not be added as it is " + "nil: " + record.number, scope), + false); + } } } - reader.close(); } catch (final IOException e2) { throw GamaRuntimeException.create(e2, scope); diff --git a/msi.gama.core/src/msi/gama/util/file/GamlFileInfo.java b/msi.gama.core/src/msi/gama/util/file/GamlFileInfo.java index 737998a097..4559cf30a1 100644 --- a/msi.gama.core/src/msi/gama/util/file/GamlFileInfo.java +++ b/msi.gama.core/src/msi/gama/util/file/GamlFileInfo.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * GamlFileInfo.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform - * (v.1.8.2). + * GamlFileInfo.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.file; @@ -24,10 +24,10 @@ public class GamlFileInfo extends GamaFileMetaData { /** The batch prefix. */ - public static String BATCH_PREFIX = "***"; + public static final String BATCH_PREFIX = "***"; /** The errors. */ - public static String ERRORS = "errors detected"; + public static final String ERRORS = "errors detected"; /** The experiments. */ private final Collection experiments; diff --git a/msi.gama.core/src/msi/gama/util/file/csv/CsvReader.java b/msi.gama.core/src/msi/gama/util/file/csv/CsvReader.java index 4c59940523..73e886100b 100644 --- a/msi.gama.core/src/msi/gama/util/file/csv/CsvReader.java +++ b/msi.gama.core/src/msi/gama/util/file/csv/CsvReader.java @@ -495,8 +495,8 @@ public static class Stats { /** The headers. */ public String[] headers = null; - /** The qualifier. */ - public Character qualifier; + // /** The qualifier. */ + // public Character qualifier; /** The first line type. */ private IType firstLineType = Types.NO_TYPE; diff --git a/msi.gama.core/src/msi/gama/util/graph/GamaGraph.java b/msi.gama.core/src/msi/gama/util/graph/GamaGraph.java index 8efaf838a9..2eaeeca32b 100644 --- a/msi.gama.core/src/msi/gama/util/graph/GamaGraph.java +++ b/msi.gama.core/src/msi/gama/util/graph/GamaGraph.java @@ -1,11 +1,12 @@ /******************************************************************************************************* * - * GamaGraph.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * GamaGraph.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gama.util.graph; @@ -274,8 +275,9 @@ public GamaGraph(final IScope scope, final boolean directed, final IType nodeTyp * @param edgeType * the edge type */ - public GamaGraph(final IScope scope, final IContainer edgesOrVertices, final boolean byEdge, final boolean directed, final boolean uniqueEdge, - final VertexRelationship rel, final ISpecies edgesSpecies, final IType nodeType, final IType edgeType) { + public GamaGraph(final IScope scope, final IContainer edgesOrVertices, final boolean byEdge, final boolean directed, + final boolean uniqueEdge, final VertexRelationship rel, final ISpecies edgesSpecies, final IType nodeType, + final IType edgeType) { vertexMap = GamaMapFactory.create(); edgeMap = GamaMapFactory.create(); shortestPathComputed = new ConcurrentHashMap<>(); @@ -332,9 +334,11 @@ public GamaGraph(final IScope scope, final AbstractBaseGraph listAgt = nodeS.getPopulation(scope).createAgents(scope, 1, atts, false, false, null); IAgent ag = listAgt.get(0); - if (v != null) { ag.setName(v.toString()); } - addVertex(ag); - verticesAg.put(v.toString(), ag); + if (v != null) { + ag.setName(v.toString()); + addVertex(ag); + verticesAg.put(v.toString(), ag); + } } } for (DefaultEdge e : graph.edgeSet()) { @@ -436,7 +440,8 @@ public GamaGraph(final IScope scope, final AbstractBaseGraph vertices, boolean uniqueEdge) { + protected void buildByVertices(final IScope scope, final IContainer vertices, final boolean uniqueEdge) { for (final E p : vertices.iterable(scope)) { addVertex(p); } } @@ -1480,12 +1486,8 @@ public IGraph copy(final IScope scope) { Graphs.addAllVertices(g, this.getVertices()); Graphs.addAllEdges(g, this, this.edgeSet()); - for(Object obj : getVertices()) { - g.setVertexWeight(obj, getWeightOf(obj)); - } - for(Object obj : getEdges()) { - g.setEdgeWeight(obj, getWeightOf(obj)); - } + for (Object obj : getVertices()) { g.setVertexWeight(obj, getWeightOf(obj)); } + for (Object obj : getEdges()) { g.setEdgeWeight(obj, getWeightOf(obj)); } return g; } diff --git a/msi.gama.core/src/msi/gama/util/matrix/GamaField.java b/msi.gama.core/src/msi/gama/util/matrix/GamaField.java index 93fb524927..44e1308793 100644 --- a/msi.gama.core/src/msi/gama/util/matrix/GamaField.java +++ b/msi.gama.core/src/msi/gama/util/matrix/GamaField.java @@ -1,3 +1,12 @@ +/******************************************************************************************************* + * + * GamaField.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.util.matrix; import static msi.gaml.types.GamaGeometryType.buildRectangle; @@ -13,7 +22,6 @@ import msi.gama.common.interfaces.IKeyword; import msi.gama.metamodel.shape.GamaPoint; import msi.gama.metamodel.shape.GamaShape; - import msi.gama.metamodel.shape.IShape; import msi.gama.precompiler.GamlAnnotations.doc; import msi.gama.precompiler.GamlAnnotations.operator; @@ -31,22 +39,48 @@ import one.util.streamex.DoubleStreamEx; import one.util.streamex.StreamEx; +/** + * The Class GamaField. + */ public class GamaField extends GamaFloatMatrix implements IField { + /** The world dimensions. */ GamaPoint worldDimensions = null; + + /** The cell dimensions. */ GamaPoint cellDimensions = null; + + /** The no data value. */ double epsilon, noDataValue; + + /** The bands. */ IList bands = GamaListFactory.create(Types.FIELD); + /** + * Instantiates a new gama field. + * + * @param scope + * the scope + * @param provider + * the provider + */ public GamaField(final IScope scope, final IFieldMatrixProvider provider) { this(scope, provider.getCols(scope), provider.getRows(scope), provider.getFieldData(scope), provider.getNoData(scope)); int nbBands = provider.getBandsNumber(scope); - for (int i = 0; i < nbBands; i++) { - bands.add(new GamaField(scope, this, provider.getBand(scope, i))); - } + for (int i = 0; i < nbBands; i++) { bands.add(new GamaField(scope, this, provider.getBand(scope, i))); } } + /** + * Instantiates a new gama field. + * + * @param scope + * the scope + * @param primary + * the primary + * @param band + * the band + */ private GamaField(final IScope scope, final GamaField primary, final double[] band) { this(scope, primary.numCols, primary.numRows, band, primary.noDataValue); worldDimensions = primary.worldDimensions; @@ -54,6 +88,20 @@ private GamaField(final IScope scope, final GamaField primary, final double[] ba epsilon = primary.epsilon; } + /** + * Instantiates a new gama field. + * + * @param scope + * the scope + * @param cols + * the cols + * @param rows + * the rows + * @param objects + * the objects + * @param noDataValue + * the no data value + */ public GamaField(final IScope scope, final int cols, final int rows, final double[] objects, final double noDataValue) { super(objects); // no copy @@ -78,14 +126,35 @@ private void computeDimensions(final IScope scope) { epsilon = cellDimensions.x / 1000; } + /** + * Gets the grid X. + * + * @param x + * the x + * @return the grid X + */ int getGridX(final double x) { return (int) ((x == worldDimensions.x ? x - epsilon : x) / cellDimensions.x); } + /** + * Gets the grid Y. + * + * @param y + * the y + * @return the grid Y + */ int getGridY(final double y) { return (int) ((y == worldDimensions.y ? y - epsilon : y) / cellDimensions.y); } + /** + * Gets the index. + * + * @param p + * the p + * @return the index + */ int getIndex(final GamaPoint p) { return getGridY(p.y) * numCols + getGridX(p.x); } @@ -96,10 +165,8 @@ public Double getFromIndicesList(final IScope scope, final IList indices) throws final int size = indices.size(); if (size == 1) { final Object index = indices.get(0); - if (index instanceof GamaPoint) - return get(scope, (GamaPoint) index); - else - return matrix[Cast.asInt(scope, index)]; + if (index instanceof GamaPoint) return get(scope, (GamaPoint) index); + return matrix[Cast.asInt(scope, index)]; } return get(scope, Cast.asInt(scope, indices.get(0)), Cast.asInt(scope, indices.get(1))); } @@ -154,11 +221,7 @@ public double getNoData(final IScope scope) { @Override public void setNoData(final IScope scope, final double noData) { if (noData != noDataValue) { noDataValue = noData; } - if (bands.size() > 1) { - for (int i = 1; i < bands.size(); i++) { - bands.get(i).setNoData(scope, noData); - } - } + if (bands.size() > 1) { for (int i = 1; i < bands.size(); i++) { bands.get(i).setNoData(scope, noData); } } } @Override @@ -205,9 +268,7 @@ public void setValueAtIndex(final IScope scope, final int i, final String var_di @Override public void getValuesInto(final IScope scope, final String varName, final double minValue, final double[] input) { System.arraycopy(matrix, 0, input, 0, input.length); - for (int i = 0; i < input.length; i++) { - if (input[i] < minValue) { input[i] = 0; } - } + for (int i = 0; i < input.length; i++) { if (input[i] < minValue) { input[i] = 0; } } } /** @@ -234,7 +295,7 @@ public java.lang.Iterable iterable(final IScope scope) { @Override public IShape getCellShapeAt(final IScope scope, final GamaPoint at) { computeDimensions(scope); - final GamaPoint p = (GamaPoint) at; + final GamaPoint p = at; return getCellShapeAt(scope, getGridX(p.x), getGridY(p.y)); } @@ -334,18 +395,16 @@ public int getBandsNumber(final IScope scope) { @Override public GamaField copy(final IScope scope, final GamaPoint size, final boolean copy) { if (size == null) { - if (copy) { - GamaField result = new GamaField(scope, numCols, numRows, - Arrays.copyOf(getMatrix(), getMatrix().length), noDataValue); - if (bands.size() > 1) { - for (GamaField f : bands) { - result.bands.add(new GamaField(scope, numCols, numRows, - Arrays.copyOf(f.getMatrix(), f.getMatrix().length), noDataValue)); - } + if (!copy) return this; + GamaField result = + new GamaField(scope, numCols, numRows, Arrays.copyOf(getMatrix(), getMatrix().length), noDataValue); + if (bands.size() > 1) { + for (GamaField f : bands) { + result.bands.add(new GamaField(scope, numCols, numRows, + Arrays.copyOf(f.getMatrix(), f.getMatrix().length), noDataValue)); } - return result; - } else - return this; + } + return result; } GamaField result = new GamaField(scope, (int) size.getX(), (int) size.getY(), Arrays.copyOf(getMatrix(), getMatrix().length), noDataValue); @@ -372,9 +431,7 @@ public GamaField plus(final IScope scope, final IMatrix other) throws GamaRuntim // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) if (other instanceof GamaFloatMatrix) { GamaFloatMatrix nm = (GamaFloatMatrix) other; - for (int i = 0; i < matrix.length; i++) { - matrix[i] += nm.matrix[i]; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] += nm.matrix[i]; } } return this; } @@ -393,9 +450,7 @@ public GamaField minus(final IScope scope, final IMatrix other) throws GamaRunti // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) if (other instanceof GamaFloatMatrix) { GamaFloatMatrix nm = (GamaFloatMatrix) other; - for (int i = 0; i < matrix.length; i++) { - matrix[i] -= nm.matrix[i]; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] -= nm.matrix[i]; } } return this; } @@ -412,9 +467,7 @@ public GamaField minus(final IScope scope, final IMatrix other) throws GamaRunti @Override public GamaField times(final Double val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] *= val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] *= val; } return this; } @@ -430,9 +483,7 @@ public GamaField times(final Double val) throws GamaRuntimeException { @Override public GamaField times(final Integer val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] *= val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] *= val; } return this; } @@ -448,9 +499,7 @@ public GamaField times(final Integer val) throws GamaRuntimeException { @Override public GamaField divides(final Double val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] /= val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] /= val; } return this; } @@ -466,9 +515,7 @@ public GamaField divides(final Double val) throws GamaRuntimeException { @Override public GamaField divides(final Integer val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] /= val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] /= val; } return this; } @@ -484,9 +531,7 @@ public GamaField divides(final Integer val) throws GamaRuntimeException { @Override public GamaField plus(final Double val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] += val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] += val; } return this; } @@ -502,9 +547,7 @@ public GamaField plus(final Double val) throws GamaRuntimeException { @Override public GamaField plus(final Integer val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] += val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] += val; } return this; } @@ -520,9 +563,7 @@ public GamaField plus(final Integer val) throws GamaRuntimeException { @Override public GamaField minus(final Double val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] -= val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] -= val; } return this; } @@ -538,15 +579,12 @@ public GamaField minus(final Double val) throws GamaRuntimeException { @Override public GamaField minus(final Integer val) throws GamaRuntimeException { // No check for best performances. Errors will be emitted by the various sub-operations (out of bounds, etc.) - for (int i = 0; i < matrix.length; i++) { - matrix[i] -= val; - } + for (int i = 0; i < matrix.length; i++) { matrix[i] -= val; } return this; } + @SuppressWarnings ("unchecked") @Override - public IContainerType getGamlType() { - return Types.FIELD; - } + public IContainerType getGamlType() { return Types.FIELD; } } diff --git a/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java b/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java index bb7717dc7b..5dd0d47b4b 100644 --- a/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java +++ b/msi.gama.core/src/msi/gama/util/matrix/GamaObjectMatrix.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gama.util.matrix.GamaObjectMatrix.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling - * and simulation platform (v. 1.8.1) + * GamaObjectMatrix.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -34,8 +34,22 @@ import msi.gaml.types.Types; import one.util.streamex.StreamEx; +/** + * The Class GamaObjectMatrix. + */ public class GamaObjectMatrix extends GamaMatrix { + /** + * From. + * + * @param c + * the c + * @param r + * the r + * @param m + * the m + * @return the gama object matrix + */ static public GamaObjectMatrix from(final int c, final int r, final IMatrix m) { if (m instanceof GamaFloatMatrix) return new GamaObjectMatrix(c, r, ((GamaFloatMatrix) m).getMatrix()); if (m instanceof GamaObjectMatrix) @@ -49,38 +63,96 @@ static public GamaObjectMatrix from(final int c, final int r, final IMatrix m /** The matrix. */ protected Object[] matrix; + /** + * Instantiates a new gama object matrix. + * + * @param p + * the p + * @param contentsType + * the contents type + */ public GamaObjectMatrix(final GamaPoint p, final IType contentsType) { this((int) p.getX(), (int) p.getY(), contentsType); } + /** + * Instantiates a new gama object matrix. + * + * @param cols + * the cols + * @param rows + * the rows + * @param contentsType + * the contents type + */ public GamaObjectMatrix(final int cols, final int rows, final IType contentsType) { super(cols, rows, contentsType); setMatrix(new Object[cols * rows]); } + /** + * Instantiates a new gama object matrix. + * + * @param cols + * the cols + * @param rows + * the rows + * @param objects + * the objects + */ public GamaObjectMatrix(final int cols, final int rows, final double[] objects) { this(cols, rows, Types.FLOAT); final int n = Math.min(objects.length, rows * cols); - for (int i = 0; i < n; i++) { - matrix[i] = objects[i]; - } + for (int i = 0; i < n; i++) { matrix[i] = objects[i]; } // java.lang.System.arraycopy(objects, 0, getMatrix(), 0, // FastMath.min(objects.length, rows * cols)); } + /** + * Instantiates a new gama object matrix. + * + * @param cols + * the cols + * @param rows + * the rows + * @param objects + * the objects + */ public GamaObjectMatrix(final int cols, final int rows, final int[] objects) { this(cols, rows, Types.INT); final int n = Math.min(objects.length, rows * cols); - for (int i = 0; i < n; i++) { - matrix[i] = objects[i]; - } + for (int i = 0; i < n; i++) { matrix[i] = objects[i]; } } + /** + * Instantiates a new gama object matrix. + * + * @param cols + * the cols + * @param rows + * the rows + * @param objects + * the objects + * @param contentsType + * the contents type + */ public GamaObjectMatrix(final int cols, final int rows, final Object[] objects, final IType contentsType) { this(cols, rows, contentsType); java.lang.System.arraycopy(objects, 0, getMatrix(), 0, Math.min(objects.length, rows * cols)); } + /** + * Instantiates a new gama object matrix. + * + * @param scope + * the scope + * @param objects + * the objects + * @param preferredSize + * the preferred size + * @param contentsType + * the contents type + */ public GamaObjectMatrix(final IScope scope, final IList objects, final GamaPoint preferredSize, final IType contentsType) { super(scope, objects, preferredSize, contentsType); @@ -97,9 +169,7 @@ public GamaObjectMatrix(final IScope scope, final IList objects, final GamaPo } } else { for (int i = 0; i < numRows; i++) { - for (int j = 0; j < numCols; j++) { - set(scope, j, i, ((List) objects.get(j)).get(i)); - } + for (int j = 0; j < numCols; j++) { set(scope, j, i, ((List) objects.get(j)).get(i)); } } } } @@ -116,9 +186,7 @@ public void _clear() { @Override public boolean _contains(final IScope scope, final Object o) { - for (int i = 0; i < getMatrix().length; i++) { - if (getMatrix()[i].equals(o)) return true; - } + for (int i = 0; i < getMatrix().length; i++) { if (getMatrix()[i].equals(o)) return true; } return false; } @@ -221,16 +289,14 @@ public GamaObjectMatrix _opAppendHorizontally(final IScope scope, final IMatrix< // @Override public boolean _isEmpty(final IScope scope) { - for (int i = 0; i < getMatrix().length; i++) { - if (getMatrix()[i] != null) return false; - } + for (int i = 0; i < getMatrix().length; i++) { if (getMatrix()[i] != null) return false; } return true; } @Override protected IList _listValue(final IScope scope, final IType contentsType, final boolean cast) { return cast ? GamaListFactory.create(scope, contentsType, getMatrix()) - : GamaListFactory.wrap(contentsType, getMatrix()); + : GamaListFactory. wrap(contentsType, getMatrix()); } @Override @@ -243,9 +309,7 @@ protected IMatrix _matrixValue(final IScope scope, final GamaPoint prefe public GamaObjectMatrix _reverse(final IScope scope) throws GamaRuntimeException { final GamaObjectMatrix result = new GamaObjectMatrix(numRows, numCols, getGamlType().getContentType()); for (int i = 0; i < numCols; i++) { - for (int j = 0; j < numRows; j++) { - result.set(scope, j, i, get(scope, i, j)); - } + for (int j = 0; j < numRows; j++) { result.set(scope, j, i, get(scope, i, j)); } } return result; } @@ -253,11 +317,9 @@ public GamaObjectMatrix _reverse(final IScope scope) throws GamaRuntimeException @Override public GamaObjectMatrix copy(final IScope scope, final GamaPoint size, final boolean copy) { if (size == null) { - if (copy) - return new GamaObjectMatrix(numCols, numRows, Arrays.copyOf(matrix, matrix.length), - getGamlType().getContentType()); - else - return this; + if (copy) return new GamaObjectMatrix(numCols, numRows, Arrays.copyOf(matrix, matrix.length), + getGamlType().getContentType()); + return this; } return new GamaObjectMatrix((int) size.getX(), (int) size.getY(), Arrays.copyOf(matrix, matrix.length), getGamlType().getContentType()); @@ -270,17 +332,26 @@ public boolean equals(final Object m) { final GamaObjectMatrix mat = (GamaObjectMatrix) m; return Arrays.equals(this.getMatrix(), mat.getMatrix()); } + // - // @Override - // public int hashCode() { - // return super.hashCode(); - // } + @Override + public int hashCode() { + return Arrays.hashCode(getMatrix()); + } @Override public void _putAll(final IScope scope, final Object o) { fillWith(scope, getGamlType().getContentType().cast(scope, o, null, false)); } + /** + * Fill with. + * + * @param scope + * the scope + * @param o + * the o + */ public void fillWith(final IScope scope, final Object o) { // We copy the element with which to fill the matrix if it is a // (possibly) complex value @@ -376,13 +447,20 @@ public java.lang.Iterable iterable(final IScope scope) { return ImmutableList.copyOf(getMatrix()); } - public Object[] getMatrix() { - return matrix; - } + /** + * Gets the matrix. + * + * @return the matrix + */ + public Object[] getMatrix() { return matrix; } - protected void setMatrix(final Object[] matrix) { - this.matrix = matrix; - } + /** + * Sets the matrix. + * + * @param matrix + * the new matrix + */ + protected void setMatrix(final Object[] matrix) { this.matrix = matrix; } @Override protected void setNthElement(final IScope scope, final int index, final Object value) { @@ -408,9 +486,7 @@ public StreamEx stream(final IScope scope) { @Override public double[] getFieldData(final IScope scope) { double[] result = new double[matrix.length]; - for (int i = 0; i < matrix.length; ++i) { - result[i] = Cast.asFloat(scope, matrix[i]); - } + for (int i = 0; i < matrix.length; ++i) { result[i] = Cast.asFloat(scope, matrix[i]); } return result; } diff --git a/msi.gama.core/src/msi/gaml/compilation/GAML.java b/msi.gama.core/src/msi/gaml/compilation/GAML.java index 93fe641640..9d34c9051e 100644 --- a/msi.gama.core/src/msi/gaml/compilation/GAML.java +++ b/msi.gama.core/src/msi/gaml/compilation/GAML.java @@ -103,10 +103,10 @@ public class GAML { public final static HashMultimap LISTENERS_BY_NAME = HashMultimap.create(); /** The expression factory. */ - public static IExpressionFactory expressionFactory = null; + public static volatile IExpressionFactory expressionFactory = null; /** The model factory. */ - public static ModelFactory modelFactory = null; + public static volatile ModelFactory modelFactory = null; /** The info provider. */ private static IGamlResourceInfoProvider infoProvider = null; @@ -114,9 +114,6 @@ public class GAML { /** The gaml ecore utils. */ private static IGamlEcoreUtils gamlEcoreUtils = null; - /** The command index. */ - public static int COMMAND_INDEX = 0; - /** * Not null. * diff --git a/msi.gama.core/src/msi/gaml/compilation/Symbol.java b/msi.gama.core/src/msi/gaml/compilation/Symbol.java index 41706878f2..4a92136029 100644 --- a/msi.gama.core/src/msi/gaml/compilation/Symbol.java +++ b/msi.gama.core/src/msi/gaml/compilation/Symbol.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.compilation.Symbol.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * Symbol.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.compilation; @@ -18,8 +18,8 @@ import msi.gama.runtime.exceptions.GamaRuntimeException; import msi.gaml.descriptions.IDescription; import msi.gaml.descriptions.IExpressionDescription; -import msi.gaml.descriptions.SymbolDescription; import msi.gaml.expressions.IExpression; +import ummisco.gama.dev.utils.COUNTER; /** * Written by drogoul Modified on 13 mai 2010 A simple class to serve as the root of all Gaml Symbols @@ -29,64 +29,86 @@ */ public abstract class Symbol implements ISymbol { + /** The name. */ protected String name; + + /** The description. */ protected final IDescription description; + + /** The order. */ protected int order; @Override - public IDescription getDescription() { - return description; - } + public IDescription getDescription() { return description; } @Override public URI getURI() { - if (description == null) { return null; } + if (description == null) return null; final EObject object = description.getUnderlyingElement(); return object == null ? null : EcoreUtil.getURI(object); } @Override - public int getOrder() { - return order; - } + public int getOrder() { return order; } @Override - public void setOrder(final int i) { - order = i; - } + public void setOrder(final int i) { order = i; } + /** + * Instantiates a new symbol. + * + * @param desc the desc + */ public Symbol(final IDescription desc) { description = desc; if (desc != null) { order = desc.getOrder(); } else { - order = SymbolDescription.ORDER++; + order = COUNTER.GET(); // DEBUG.LOG("Order of " + desc.getName() + " = " + order); } } @Override public String serialize(final boolean includingBuiltIn) { - if (description == null) { return ""; } + if (description == null) return ""; return description.serialize(includingBuiltIn); } @Override public String getKeyword() { - if (description == null) { return null; } + if (description == null) return null; return description.getKeyword(); } @Override public final IExpression getFacet(final String... keys) { - if (description == null) { return null; } + if (description == null) return null; return description.getFacetExpr(keys); } + /** + * Gets the facet value. + * + * @param scope the scope + * @param key the key + * @return the facet value + * @throws GamaRuntimeException the gama runtime exception + */ public Object getFacetValue(final IScope scope, final String key) throws GamaRuntimeException { return getFacetValue(scope, key, null); } + /** + * Gets the facet value. + * + * @param the generic type + * @param scope the scope + * @param key the key + * @param defaultValue the default value + * @return the facet value + * @throws GamaRuntimeException the gama runtime exception + */ @SuppressWarnings ("unchecked") public final T getFacetValue(final IScope scope, final String key, final T defaultValue) throws GamaRuntimeException { @@ -94,17 +116,36 @@ public final T getFacetValue(final IScope scope, final String key, final T d return (T) (exp == null ? defaultValue : exp.value(scope)); } + /** + * Gets the literal. + * + * @param key the key + * @return the literal + */ public String getLiteral(final String key) { return getLiteral(key, null); } + /** + * Gets the literal. + * + * @param key the key + * @param defaultValue the default value + * @return the literal + */ public String getLiteral(final String key, final String defaultValue) { final IExpression exp = getFacet(key); return exp == null ? defaultValue : exp.literalValue(); } + /** + * Sets the facet. + * + * @param key the key + * @param expr the expr + */ protected void setFacet(final String key, final IExpressionDescription expr) { - if (description == null) { return; } + if (description == null) return; description.setFacet(key, expr); } @@ -114,14 +155,10 @@ public boolean hasFacet(final String s) { } @Override - public void setName(final String n) { - name = n; - } + public void setName(final String n) { name = n; } @Override - public String getName() { - return name; - } + public String getName() { return name; } @Override public void dispose() { diff --git a/msi.gama.core/src/msi/gaml/descriptions/ActionDescription.java b/msi.gama.core/src/msi/gaml/descriptions/ActionDescription.java index bb4ed27a77..a84813e348 100644 --- a/msi.gama.core/src/msi/gaml/descriptions/ActionDescription.java +++ b/msi.gama.core/src/msi/gaml/descriptions/ActionDescription.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.descriptions.ActionDescription.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * ActionDescription.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.descriptions; @@ -28,12 +28,29 @@ import msi.gaml.types.IType; import msi.gaml.types.Types; +/** + * The Class ActionDescription. + */ public class ActionDescription extends StatementWithChildrenDescription { + /** The is abstract. */ protected final boolean isAbstract; + + /** The is synthetic. */ protected final boolean isSynthetic; - public static Arguments NULL_ARGS = new Arguments(); + + /** The Constant NULL_ARGS. */ + public static final Arguments NULL_ARGS = new Arguments(); + /** + * Instantiates a new action description. + * + * @param keyword the keyword + * @param superDesc the super desc + * @param cp the cp + * @param source the source + * @param facets the facets + */ public ActionDescription(final String keyword, final IDescription superDesc, final Iterable cp, final EObject source, final Facets facets) { super(keyword, superDesc, cp, true, source, facets, null); @@ -49,27 +66,31 @@ public ActionDescription copy(final IDescription into) { return desc; } - public boolean isAbstract() { - return isAbstract; - } + /** + * Checks if is abstract. + * + * @return true, if is abstract + */ + public boolean isAbstract() { return isAbstract; } @Override - public boolean isBuiltIn() { - return super.isBuiltIn() && !isSynthetic; - } + public boolean isBuiltIn() { return super.isBuiltIn() && !isSynthetic; } @Override - protected boolean isSynthetic() { - return isSynthetic; - } + protected boolean isSynthetic() { return isSynthetic; } /** * @return */ - public List getArgNames() { - return Lists.newArrayList(Iterables.transform(getFormalArgs(), TO_NAME)); - } + public List getArgNames() { return Lists.newArrayList(Iterables.transform(getFormalArgs(), TO_NAME)); } + /** + * Verify args. + * + * @param caller the caller + * @param args the args + * @return true, if successful + */ @SuppressWarnings ("rawtypes") public boolean verifyArgs(final IDescription caller, final Arguments args) { final Arguments names = args == null ? NULL_ARGS : args; @@ -78,22 +99,20 @@ public boolean verifyArgs(final IDescription caller, final Arguments args) { if (noArgs) { final Iterable formalArgsWithoutDefault = Iterables.filter(formalArgs, each -> !each.hasFacet(DEFAULT)); - if (Iterables.isEmpty(formalArgsWithoutDefault)) { return true; } + if (Iterables.isEmpty(formalArgsWithoutDefault)) return true; } final List allArgs = getArgNames(); - if (caller.getKeyword().equals(DO) || caller.getKeyword().equals(INVOKE)) { - // If the names were not known at the time of the creation of the - // caller, only the order - if (names.containsKey("0")) { - int index = 0; - for (final String the_name : allArgs) { - final String key = String.valueOf(index++); - final IExpressionDescription old = names.get(key); - if (old != null) { - names.put(the_name, old); - names.remove(key); - } + // If the names were not known at the time of the creation of the + // caller, only the order + if ((DO.equals(caller.getKeyword()) || INVOKE.equals(caller.getKeyword())) && names.containsKey("0")) { + int index = 0; + for (final String the_name : allArgs) { + final String key = String.valueOf(index++); + final IExpressionDescription old = names.get(key); + if (old != null) { + names.put(the_name, old); + names.remove(key); } } } @@ -109,13 +128,12 @@ public boolean verifyArgs(final IDescription caller, final Arguments args) { c.getFacet(DEFAULT).compile(this); continue; } - if (c.hasFacet(OPTIONAL) && c.getFacet(OPTIONAL).equalsString(FALSE) || !c.hasFacet(OPTIONAL)) { - if (!names.containsKey(n)) { - caller.error("Missing argument " + n + " in call to " + getName() + ". Arguments passed are : " - + names, IGamlIssue.MISSING_ARGUMENT, caller.getUnderlyingElement(), n); - return false; - } - + if ((c.hasFacet(OPTIONAL) && c.getFacet(OPTIONAL).equalsString(FALSE) || !c.hasFacet(OPTIONAL)) + && !names.containsKey(n)) { + caller.error( + "Missing argument " + n + " in call to " + getName() + ". Arguments passed are : " + names, + IGamlIssue.MISSING_ARGUMENT, caller.getUnderlyingElement(), n); + return false; } } } @@ -129,7 +147,8 @@ public boolean verifyArgs(final IDescription caller, final Arguments args) { caller.error("Unknown argument " + the_name + " in call to " + getName(), IGamlIssue.UNKNOWN_ARGUMENT, arg.value.getTarget(), arg.key); return false; - } else if (arg.value != null && arg.value.getExpression() != null) { + } + if (arg.value != null && arg.value.getExpression() != null) { final IDescription formalArg = Iterables.find(formalArgs, input -> input.getName().equals(the_name)); final IType formalType = formalArg.getGamlType(); @@ -152,6 +171,12 @@ public boolean verifyArgs(final IDescription caller, final Arguments args) { return true; } + /** + * Contains arg. + * + * @param s the s + * @return true, if successful + */ public boolean containsArg(final String s) { final IDescription formalArg = Iterables.find(getFormalArgs(), input -> input.getName().equals(s)); return formalArg != null; @@ -165,9 +190,7 @@ public Arguments createCompiledArgs() { IExpression e = null; final IDescription superDesc = getEnclosingDescription(); final IExpressionDescription ed = sd.getFacet(VALUE, DEFAULT); - if (ed != null) { - e = ed.compile(superDesc); - } + if (ed != null) { e = ed.compile(superDesc); } ca.put(the_name, e); } return ca; @@ -175,10 +198,13 @@ public Arguments createCompiledArgs() { } @Override - public String getDocumentation() { - return getArgDocumentation() + super.getDocumentation(); - } + public String getDocumentation() { return getArgDocumentation() + super.getDocumentation(); } + /** + * Gets the arg documentation. + * + * @return the arg documentation + */ public String getArgDocumentation() { final StringBuilder sb = new StringBuilder(200); @@ -196,9 +222,7 @@ public String getArgDocumentation() { return sb1.toString(); })); sb.append("Arguments accepted: ").append("
    "); - for (final String a : args) { - sb.append(a); - } + for (final String a : args) { sb.append(a); } sb.append("

"); } return sb.toString(); @@ -210,10 +234,13 @@ public String getArgDocumentation() { // } @Override - public String getTitle() { - return super.getTitle() + getShortDescription(); - } + public String getTitle() { return super.getTitle() + getShortDescription(); } + /** + * Gets the short description. + * + * @return the short description + */ public String getShortDescription() { final String returns = getGamlType().equals(Types.NO_TYPE) ? ", no value returned" : ", returns a result of type " + getGamlType().getTitle(); @@ -221,9 +248,7 @@ public String getShortDescription() { for (final IDescription desc : getFormalArgs()) { args.append(desc.getGamlType()).append(" ").append(desc.getName()).append(", "); } - if (args.length() > 0) { - args.setLength(args.length() - 2); - } + if (args.length() > 0) { args.setLength(args.length() - 2); } return "(" + args.toString() + ")" + returns; diff --git a/msi.gama.core/src/msi/gaml/descriptions/ModelDescription.java b/msi.gama.core/src/msi/gaml/descriptions/ModelDescription.java index 18ae933ee2..703e4dba6a 100644 --- a/msi.gama.core/src/msi/gaml/descriptions/ModelDescription.java +++ b/msi.gama.core/src/msi/gaml/descriptions/ModelDescription.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.descriptions.ModelDescription.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling - * and simulation platform (v. 1.8.1) + * ModelDescription.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.descriptions; @@ -28,7 +28,6 @@ import msi.gama.common.interfaces.IGamlIssue; import msi.gama.common.interfaces.IKeyword; import msi.gama.kernel.simulation.SimulationAgent; -import msi.gama.metamodel.agent.IAgent; import msi.gama.util.GamaMapFactory; import msi.gama.util.IMap; import msi.gaml.compilation.IAgentConstructor; @@ -47,51 +46,113 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class ModelDescription extends SpeciesDescription { + /** The Constant MODEL_SUFFIX. */ // TODO Move elsewhere public static final String MODEL_SUFFIX = "_model"; + + /** The root. */ public static volatile ModelDescription ROOT; + + /** The built in models. */ public static volatile Map BUILT_IN_MODELS = new HashMap(); + + /** The experiments. */ private IMap experiments; + + /** The types. */ final ITypesManager types; + + /** The model file path. */ private String modelFilePath; + + /** The model project path. */ private final String modelProjectPath; + + /** The alternate paths. */ private final Set alternatePaths; + + /** The validation context. */ private final ValidationContext validationContext; + + /** The document. */ protected volatile boolean document; + + /** The micro models. */ // hqnghi new attribute manipulate micro-models private IMap microModels; + + /** The alias. */ private String alias = ""; + + /** The is starting date defined. */ boolean isStartingDateDefined = false; + + /** The imported model names. */ private Collection importedModelNames; + /** + * Gets the alternate paths. + * + * @return the alternate paths + */ public Collection getAlternatePaths() { return alternatePaths == null ? Collections.EMPTY_LIST : alternatePaths; } + /** + * Gets the micro model. + * + * @param name the name + * @return the micro model + */ public ModelDescription getMicroModel(final String name) { if (microModels == null) return null; return microModels.get(name); } - public void setAlias(final String as) { - alias = as; - } + /** + * Sets the alias. + * + * @param as the new alias + */ + public void setAlias(final String as) { alias = as; } - public String getAlias() { - return alias; - } + /** + * Gets the alias. + * + * @return the alias + */ + public String getAlias() { return alias; } - public boolean isMicroModel() { - return alias != null && !alias.isEmpty(); - } + /** + * Checks if is micro model. + * + * @return true, if is micro model + */ + public boolean isMicroModel() { return alias != null && !alias.isEmpty(); } @Override - public boolean isModel() { - return true; - } + public boolean isModel() { return true; } // end-hqnghi + /** + * Instantiates a new model description. + * + * @param name the name + * @param clazz the clazz + * @param projectPath the project path + * @param modelPath the model path + * @param source the source + * @param macro the macro + * @param parent the parent + * @param children the children + * @param facets the facets + * @param validationContext the validation context + * @param imports the imports + * @param helper the helper + * @param skills the skills + */ public ModelDescription(final String name, final Class clazz, final String projectPath, final String modelPath, final EObject source, final SpeciesDescription macro, final SpeciesDescription parent, final Iterable children, final Facets facets, @@ -108,6 +169,22 @@ public ModelDescription(final String name, final Class clazz, final String proje if (helper != null) { setAgentConstructor(helper); } } + /** + * Instantiates a new model description. + * + * @param name the name + * @param clazz the clazz + * @param projectPath the project path + * @param modelPath the model path + * @param source the source + * @param macro the macro + * @param parent the parent + * @param children the children + * @param facets the facets + * @param validationContext the validation context + * @param imports the imports + * @param helper the helper + */ public ModelDescription(final String name, final Class clazz, final String projectPath, final String modelPath, final EObject source, final SpeciesDescription macro, final SpeciesDescription parent, final Iterable children, final Facets facets, @@ -122,15 +199,16 @@ public SymbolSerializer createSerializer() { } @Override - public String getTitle() { - return getName().replace(MODEL_SUFFIX, ""); - } + public String getTitle() { return getName().replace(MODEL_SUFFIX, ""); } @Override - public boolean isDocumenting() { - return document; - } + public boolean isDocumenting() { return document; } + /** + * Checks if is documenting. + * + * @param b the b + */ public void isDocumenting(final boolean b) { document = b; } @@ -178,7 +256,7 @@ public void markAttributeRedefinition(final VariableDescription existingVar, fin public String getDocumentationWithoutMeta() { final StringBuilder sb = new StringBuilder(200); final String parentName = getParent() == null ? "nil" : getParent().getName(); - if (!parentName.equals(IKeyword.MODEL)) { + if (!IKeyword.MODEL.equals(parentName)) { sb.append("Subspecies of: ").append(parentName).append("
"); } final Iterable skills = getSkillsNames(); @@ -222,17 +300,21 @@ public void dispose() { * * @return the model file name */ - public String getModelFilePath() { - return modelFilePath; - } + public String getModelFilePath() { return modelFilePath; } - public String getModelFolderPath() { - return new File(modelFilePath).getParent(); - } + /** + * Gets the model folder path. + * + * @return the model folder path + */ + public String getModelFolderPath() { return new File(modelFilePath).getParent(); } - public String getModelProjectPath() { - return modelProjectPath; - } + /** + * Gets the model project path. + * + * @return the model project path + */ + public String getModelProjectPath() { return modelProjectPath; } /** * Create types from the species descriptions @@ -273,14 +355,23 @@ public IDescription addChild(final IDescription child) { @Override public void addOwnAttribute(final VariableDescription vd) { - if (!vd.isBuiltIn() && vd.getName().equals(SimulationAgent.STARTING_DATE)) { isStartingDateDefined = true; } + if (!vd.isBuiltIn() && SimulationAgent.STARTING_DATE.equals(vd.getName())) { isStartingDateDefined = true; } super.addOwnAttribute(vd); } - public boolean isStartingDateDefined() { - return isStartingDateDefined; - } + /** + * Checks if is starting date defined. + * + * @return true, if is starting date defined + */ + public boolean isStartingDateDefined() { return isStartingDateDefined; } + /** + * Checks for experiment. + * + * @param nameOrTitle the name or title + * @return true, if successful + */ public boolean hasExperiment(final String nameOrTitle) { if (experiments == null) return false; if (experiments.containsKey(nameOrTitle)) return true; @@ -291,21 +382,16 @@ public boolean hasExperiment(final String nameOrTitle) { } @Override - public ModelDescription getModelDescription() { - return this; - } + public ModelDescription getModelDescription() { return this; } @Override public SpeciesDescription getSpeciesDescription(final String spec) { - if (spec.equals(getName())) return this; - if (importedModelNames != null && importedModelNames.contains(spec)) return this; - if (getTypesManager() == null) { - if (hasMicroSpecies()) - return getMicroSpecies().get(spec); - else - return null; - } else - return getTypesManager().get(spec).getSpecies(); + if (spec.equals(getName()) || (importedModelNames != null && importedModelNames.contains(spec))) return this; + if (getTypesManager() != null) return getTypesManager().get(spec).getSpecies(); + if (hasMicroSpecies()) + return getMicroSpecies().get(spec); + else + return null; } @Override @@ -314,20 +400,31 @@ public IType getTypeNamed(final String s) { return types.get(s); } - public ITypesManager getTypesManager() { - return types; - } + /** + * Gets the types manager. + * + * @return the types manager + */ + public ITypesManager getTypesManager() { return types; } @Override - public SpeciesDescription getSpeciesContext() { - return this; - } + public SpeciesDescription getSpeciesContext() { return this; } + /** + * Gets the experiment names. + * + * @return the experiment names + */ public Set getExperimentNames() { if (experiments == null) return Collections.EMPTY_SET; return new LinkedHashSet(experiments.keySet()); } + /** + * Gets the experiment titles. + * + * @return the experiment titles + */ public Set getExperimentTitles() { final Set strings = new LinkedHashSet(); if (experiments != null) { @@ -340,10 +437,14 @@ public Set getExperimentTitles() { } @Override - public ValidationContext getValidationContext() { - return validationContext; - } + public ValidationContext getValidationContext() { return validationContext; } + /** + * Gets the experiment. + * + * @param name the name + * @return the experiment + */ public ExperimentDescription getExperiment(final String name) { if (experiments == null) return null; final ExperimentDescription desc = experiments.get(name); @@ -364,8 +465,7 @@ public boolean visitChildren(final DescriptionVisitor visitor) { @Override public boolean visitOwnChildren(final DescriptionVisitor visitor) { - if (!super.visitOwnChildren(visitor)) return false; - if (experiments != null) { if (!experiments.forEachValue(visitor)) return false; } + if (!super.visitOwnChildren(visitor) || ((experiments != null) && !experiments.forEachValue(visitor))) return false; return true; } @@ -375,8 +475,7 @@ public boolean visitOwnChildrenRecursively(final DescriptionVisitor getExperiments() { return experiments.values(); } - public void setImportedModelNames(final Collection allModelNames) { - importedModelNames = allModelNames; - } + /** + * Sets the imported model names. + * + * @param allModelNames the new imported model names + */ + public void setImportedModelNames(final Collection allModelNames) { importedModelNames = allModelNames; } /** * Returns all the species including the model itself, all the micro-species and the experiments @@ -443,6 +551,12 @@ public boolean process(final SpeciesDescription desc) { // } } + /** + * Gets the all species. + * + * @param accumulator the accumulator + * @return the all species + */ public void getAllSpecies(final List accumulator) { final DescriptionVisitor visitor = desc -> { accumulator.add(desc); @@ -451,11 +565,6 @@ public void getAllSpecies(final List accumulator) { visitAllSpecies(visitor); } - @Override - public Class getJavaBase() { - return super.getJavaBase(); - } - @Override protected boolean parentIsVisible() { if (!getParent().isModel()) return false; diff --git a/msi.gama.core/src/msi/gaml/descriptions/SkillDescription.java b/msi.gama.core/src/msi/gaml/descriptions/SkillDescription.java index 1b31d0b137..addfac455a 100644 --- a/msi.gama.core/src/msi/gaml/descriptions/SkillDescription.java +++ b/msi.gama.core/src/msi/gaml/descriptions/SkillDescription.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.descriptions.SkillDescription.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling - * and simulation platform (v. 1.8.1) + * SkillDescription.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.descriptions; @@ -20,12 +20,28 @@ import msi.gaml.architecture.IArchitecture; import msi.gaml.skills.Skill; +/** + * The Class SkillDescription. + */ public class SkillDescription extends TypeDescription { + /** The instance. */ Skill instance; + + /** The is control. */ final boolean isControl; + + /** The java base. */ final Class javaBase; + /** + * Instantiates a new skill description. + * + * @param name the name + * @param support the support + * @param children the children + * @param plugin the plugin + */ public SkillDescription(final String name, final Class support, final Iterable children, final String plugin) { super(IKeyword.SKILL, support, null, null, children, null, null, plugin); @@ -36,14 +52,10 @@ public SkillDescription(final String name, final Class support } @Override - public Class getJavaBase() { - return javaBase; - } + public Class getJavaBase() { return javaBase; } @Override - public String getName() { - return name; - } + public String getName() { return name; } @Override public IDescription addChild(final IDescription child) { @@ -57,20 +69,23 @@ public IDescription addChild(final IDescription child) { } @Override - public boolean visitChildren(final DescriptionVisitor visitor) { + public boolean visitChildren(final DescriptionVisitor visitor) { return visitOwnChildren(visitor); } @Override - public Collection getActionNames() { - return actions == null ? Collections.EMPTY_LIST : actions.keySet(); - } + public Collection getActionNames() { return actions == null ? Collections.EMPTY_LIST : actions.keySet(); } @Override public Collection getAttributeNames() { return attributes == null ? Collections.EMPTY_LIST : attributes.keySet(); } + /** + * Creates the instance. + * + * @return the skill + */ public Skill createInstance() { Skill instance = null; try { @@ -80,20 +95,25 @@ public Skill createInstance() { return instance; } + /** + * Gets the single instance of SkillDescription. + * + * @return single instance of SkillDescription + */ public Skill getInstance() { - if (instance == null) - instance = createInstance(); + if (instance == null) { instance = createInstance(); } return instance; } - public boolean isControl() { - return isControl; - } + /** + * Checks if is control. + * + * @return true, if is control + */ + public boolean isControl() { return isControl; } @Override - public String getTitle() { - return "skill " + getName(); - } + public String getTitle() { return "skill " + getName(); } @Override public String getDocumentation() { @@ -121,27 +141,33 @@ public String getDocumentation() { } + /** + * Gets the doc annotation. + * + * @return the doc annotation + */ public doc getDocAnnotation() { skill s = javaBase.getAnnotation(skill.class); doc[] docs = s.doc(); doc d = null; if (docs.length == 0) { - if (javaBase.isAnnotationPresent(doc.class)) { - d = javaBase.getAnnotation(doc.class); - } + if (javaBase.isAnnotationPresent(doc.class)) { d = javaBase.getAnnotation(doc.class); } } else { d = docs[0]; } return d; } + /** + * Gets the deprecated. + * + * @return the deprecated + */ public String getDeprecated() { doc d = getDocAnnotation(); - if (d == null) - return null; + if (d == null) return null; String s = d.deprecated(); - if (s == null || s.isEmpty()) - return null; + if (s == null || s.isEmpty()) return null; return s; } diff --git a/msi.gama.core/src/msi/gaml/descriptions/StatementDescription.java b/msi.gama.core/src/msi/gaml/descriptions/StatementDescription.java index c58b0fd0c5..812adad440 100644 --- a/msi.gama.core/src/msi/gaml/descriptions/StatementDescription.java +++ b/msi.gama.core/src/msi/gaml/descriptions/StatementDescription.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.descriptions.StatementDescription.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * StatementDescription.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -29,6 +29,7 @@ import msi.gaml.types.GamaType; import msi.gaml.types.IType; import msi.gaml.types.Types; +import ummisco.gama.dev.utils.COUNTER; /** * Written by drogoul Modified on 10 févr. 2010 @@ -39,9 +40,26 @@ @SuppressWarnings ({ "rawtypes" }) public class StatementDescription extends SymbolDescription { + /** The passed args. */ // Corresponds to the "with" facet protected final Arguments passedArgs; + /** + * Instantiates a new statement description. + * + * @param keyword + * the keyword + * @param superDesc + * the super desc + * @param hasArgs + * the has args + * @param source + * the source + * @param facets + * the facets + * @param alreadyComputedArgs + * the already computed args + */ public StatementDescription(final String keyword, final IDescription superDesc, final boolean hasArgs, final EObject source, final Facets facets, final Arguments alreadyComputedArgs) { super(keyword, superDesc, source, /* children, */ facets); @@ -61,37 +79,49 @@ public void dispose() { if (passedArgs != null) { passedArgs.dispose(); } } + /** + * Creates the args. + * + * @return the arguments + */ private Arguments createArgs() { if (!hasFacets()) return null; - if (!hasFacet(WITH)) { - if (!isInvocation()) return null; - if (hasFacetsNotIn(DO_FACETS)) { - final Arguments args = new Arguments(); - visitFacets((facet, b) -> { - if (!DO_FACETS.contains(facet)) { args.put(facet, b); } - return true; - }); - return args; - } else - return null; - } else { + if (hasFacet(WITH)) { try { return GAML.getExpressionFactory().createArgumentMap(getAction(), getFacet(WITH), this); } finally { removeFacets(WITH); } } + if (!isInvocation() || !hasFacetsNotIn(DO_FACETS)) return null; + final Arguments args = new Arguments(); + visitFacets((facet, b) -> { + if (!DO_FACETS.contains(facet)) { args.put(facet, b); } + return true; + }); + return args; } - public boolean isSuperInvocation() { - return INVOKE.equals(keyword); - } - - private boolean isInvocation() { - return DO.equals(keyword) || isSuperInvocation(); - } - + /** + * Checks if is super invocation. + * + * @return true, if is super invocation + */ + public boolean isSuperInvocation() { return INVOKE.equals(keyword); } + + /** + * Checks if is invocation. + * + * @return true, if is invocation + */ + private boolean isInvocation() { return DO.equals(keyword) || isSuperInvocation(); } + + /** + * Gets the action. + * + * @return the action + */ private ActionDescription getAction() { final String actionName = getLitteral(ACTION); if (actionName == null) return null; @@ -128,19 +158,32 @@ public boolean manipulatesVar(final String nm) { return false; } + /** + * Verify args. + * + * @param args + * the args + * @return true, if successful + */ public boolean verifyArgs(final Arguments args) { final ActionDescription executer = getAction(); if (executer == null) return false; return executer.verifyArgs(this, args); } - public Iterable getFormalArgs() { - return getChildrenWithKeyword(ARG); - } + /** + * Gets the formal args. + * + * @return the formal args + */ + public Iterable getFormalArgs() { return getChildrenWithKeyword(ARG); } - public Facets getPassedArgs() { - return passedArgs == null ? Facets.NULL : passedArgs; - } + /** + * Gets the passed args. + * + * @return the passed args + */ + public Facets getPassedArgs() { return passedArgs == null ? Facets.NULL : passedArgs; } @Override public String getName() { @@ -153,7 +196,7 @@ public String getName() { if (REFLEX.equals(getKeyword())) { warning("Reflexes should be named", MISSING_NAME, getUnderlyingElement()); } - s = INTERNAL + getKeyword() + String.valueOf(GAML.COMMAND_INDEX++); + s = INTERNAL + getKeyword() + String.valueOf(COUNTER.GET()); } setName(s); } @@ -193,6 +236,11 @@ public IDescription validate() { return result; } + /** + * Validate passed args. + * + * @return the arguments + */ public Arguments validatePassedArgs() { final IDescription superDesc = getEnclosingDescription(); passedArgs.forEachFacet((nm, exp) -> { @@ -205,6 +253,12 @@ public Arguments validatePassedArgs() { return passedArgs; } + /** + * Verify inits. + * + * @param ca + * the ca + */ private void verifyInits(final Arguments ca) { final SpeciesDescription denotedSpecies = getGamlType().getDenotedSpecies(); if (denotedSpecies == null) { @@ -223,25 +277,23 @@ private void verifyInits(final Arguments ca) { error("Attribute " + nm + " does not exist in species " + denotedSpecies.getName(), UNKNOWN_ARGUMENT, exp.getTarget(), (String[]) null); return false; - } else { - IType initType = NO_TYPE; - IType varType = NO_TYPE; - final VariableDescription vd = denotedSpecies.getAttribute(nm); - if (vd != null) { varType = vd.getGamlType(); } - if (exp != null) { - final IExpression expr = exp.getExpression(); - if (expr != null) { initType = expr.getGamlType(); } - if (varType != NO_TYPE && !initType.isTranslatableInto(varType)) { - if (CREATE.equals(getKeyword())) { - final boolean isDB = getFacet(FROM) != null - && getFacet(FROM).getExpression().getGamlType().isAssignableFrom(Types.LIST); - if (isDB && initType.equals(Types.STRING)) return true; - } - warning("The type of attribute " + nm + " should be " + varType, SHOULD_CAST, exp.getTarget(), - varType.toString()); + } + IType initType = NO_TYPE; + IType varType = NO_TYPE; + final VariableDescription vd = denotedSpecies.getAttribute(nm); + if (vd != null) { varType = vd.getGamlType(); } + if (exp != null) { + final IExpression expr = exp.getExpression(); + if (expr != null) { initType = expr.getGamlType(); } + if (varType != NO_TYPE && !initType.isTranslatableInto(varType)) { + if (CREATE.equals(getKeyword())) { + final boolean isDB = getFacet(FROM) != null + && getFacet(FROM).getExpression().getGamlType().isAssignableFrom(Types.LIST); + if (isDB && initType.equals(Types.STRING)) return true; } + warning("The type of attribute " + nm + " should be " + varType, SHOULD_CAST, exp.getTarget(), + varType.toString()); } - } return true; @@ -299,6 +351,15 @@ protected IExpression createVarWithTypes(final String tag) { } + /** + * Adds the new temp if necessary. + * + * @param facetName + * the facet name + * @param type + * the type + * @return the i var expression + */ public IVarExpression addNewTempIfNecessary(final String facetName, final IType type) { final String varName = getLitteral(facetName); final IDescription sup = getEnclosingDescription(); @@ -320,10 +381,13 @@ public boolean visitOwnChildren(final DescriptionVisitor visitor) } @Override - public Iterable getOwnChildren() { - return EMPTY_LIST; - } + public Iterable getOwnChildren() { return EMPTY_LIST; } + /** + * Creates the compiled args. + * + * @return the arguments + */ public Arguments createCompiledArgs() { return passedArgs; } diff --git a/msi.gama.core/src/msi/gaml/descriptions/SymbolDescription.java b/msi.gama.core/src/msi/gaml/descriptions/SymbolDescription.java index a89f36fcc2..6021c9112c 100644 --- a/msi.gama.core/src/msi/gaml/descriptions/SymbolDescription.java +++ b/msi.gama.core/src/msi/gaml/descriptions/SymbolDescription.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * SymbolDescription.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * SymbolDescription.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.descriptions; @@ -34,6 +34,7 @@ import msi.gaml.types.GamaType; import msi.gaml.types.IType; import msi.gaml.types.Types; +import ummisco.gama.dev.utils.COUNTER; import ummisco.gama.dev.utils.DEBUG; /** @@ -49,10 +50,7 @@ public abstract class SymbolDescription implements IDescription { .copyOf(Arrays.asList(VALUE, TYPE, AS, SPECIES, OF, OVER, FROM, INDEX, FUNCTION, UPDATE, INIT, DEFAULT)); /** The order. */ - public static int ORDER = 0; - - /** The order. */ - private final int order = ORDER++; + private final int order = COUNTER.GET(); /** The facets. */ private Facets facets; diff --git a/msi.gama.core/src/msi/gaml/descriptions/ValidationContext.java b/msi.gama.core/src/msi/gaml/descriptions/ValidationContext.java index 797b2d1185..7500b3cbe0 100644 --- a/msi.gama.core/src/msi/gaml/descriptions/ValidationContext.java +++ b/msi.gama.core/src/msi/gaml/descriptions/ValidationContext.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.descriptions.ValidationContext.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * ValidationContext.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.descriptions; @@ -27,15 +27,36 @@ import msi.gaml.compilation.GamlCompilationError; import one.util.streamex.StreamEx; +/** + * The Class ValidationContext. + */ public class ValidationContext extends Collector.AsList implements IDocManager { + /** The Constant MAX_SIZE. */ final static int MAX_SIZE = 1000; + + /** The Constant NULL. */ public static final ValidationContext NULL = new ValidationContext(null, false, IDocManager.NULL); + + /** The resource URI. */ final URI resourceURI; + + /** The imported errors. */ final Collector.AsList importedErrors = Collector.getList(); + + /** The no experiment. */ private boolean noWarning, noInfo, hasSyntaxErrors, noExperiment; + + /** The doc delegate. */ private final IDocManager docDelegate; + /** + * Instantiates a new validation context. + * + * @param uri the uri + * @param syntax the syntax + * @param delegate the delegate + */ public ValidationContext(final URI uri, final boolean syntax, final IDocManager delegate) { this.resourceURI = uri; hasSyntaxErrors = syntax; @@ -45,60 +66,99 @@ public ValidationContext(final URI uri, final boolean syntax, final IDocManager @Override public boolean add(final GamlCompilationError error) { if (error.isWarning()) { - if (!GamaPreferences.Modeling.WARNINGS_ENABLED.getValue() || noWarning) { return false; } - } else if (error.isInfo()) { - if (!GamaPreferences.Modeling.INFO_ENABLED.getValue() || noInfo) { return false; } - } + if (!GamaPreferences.Modeling.WARNINGS_ENABLED.getValue() || noWarning) return false; + } else if (error.isInfo() && (!GamaPreferences.Modeling.INFO_ENABLED.getValue() || noInfo)) return false; final URI uri = error.getURI(); final boolean sameResource = uri.equals(resourceURI); - if (sameResource) { - return super.add(error); - } else if (error.isError()) { + if (sameResource) return super.add(error); + if (error.isError()) { importedErrors.add(error); return true; } return false; } - public static Predicate IS_INFO = input -> input.isInfo(); - public static Predicate IS_WARNING = input -> input.isWarning(); - public static Predicate IS_ERROR = input -> input.isError(); + /** The Constant IS_INFO. */ + public static final Predicate IS_INFO = GamlCompilationError::isInfo; + + /** The Constant IS_WARNING. */ + public static final Predicate IS_WARNING = GamlCompilationError::isWarning; + + /** The Constant IS_ERROR. */ + public static final Predicate IS_ERROR = GamlCompilationError::isError; + /** + * Checks for internal syntax errors. + * + * @return true, if successful + */ public boolean hasInternalSyntaxErrors() { return hasSyntaxErrors; } + /** + * Checks for internal syntax errors. + * + * @param errors the errors + */ public void hasInternalSyntaxErrors(final boolean errors) { hasSyntaxErrors = errors; } + /** + * Checks for errors. + * + * @return true, if successful + */ public boolean hasErrors() { return hasSyntaxErrors || hasInternalErrors() || hasImportedErrors(); } + /** + * Checks for internal errors. + * + * @return true, if successful + */ public boolean hasInternalErrors() { return !isEmpty() && StreamEx.of(items()).filter(IS_ERROR).count() > 0; } + /** + * Checks for imported errors. + * + * @return true, if successful + */ public boolean hasImportedErrors() { return !importedErrors.isEmpty(); } - public List getInternalErrors() { - return StreamEx.of(items()).filter(IS_ERROR).toList(); - } + /** + * Gets the internal errors. + * + * @return the internal errors + */ + public List getInternalErrors() { return StreamEx.of(items()).filter(IS_ERROR).toList(); } - public Collection getImportedErrors() { - return importedErrors.items(); - } + /** + * Gets the imported errors. + * + * @return the imported errors + */ + public Collection getImportedErrors() { return importedErrors.items(); } - public Iterable getWarnings() { - return StreamEx.of(items()).filter(IS_WARNING).toList(); - } + /** + * Gets the warnings. + * + * @return the warnings + */ + public Iterable getWarnings() { return StreamEx.of(items()).filter(IS_WARNING).toList(); } - public Iterable getInfos() { - return StreamEx.of(items()).filter(IS_INFO).toList(); - } + /** + * Gets the infos. + * + * @return the infos + */ + public Iterable getInfos() { return StreamEx.of(items()).filter(IS_INFO).toList(); } @Override public void clear() { @@ -117,20 +177,34 @@ public Iterator iterator() { return StreamEx.of(items()).append(getImportedErrors()).limit(MAX_SIZE).toList().iterator(); } + /** + * Gets the imported errors as strings. + * + * @return the imported errors as strings + */ public Map getImportedErrorsAsStrings() { return StreamEx.of(importedErrors).toMap(e -> e.toString() + " (" + URI.decode(e.getURI().lastSegment()) + ")", - e -> e.getURI(), (t, u) -> t); + GamlCompilationError::getURI, (t, u) -> t); } + /** + * Sets the no warning. + */ public void setNoWarning() { noWarning = true; } + /** + * Sets the no info. + */ public void setNoInfo() { noInfo = true; } + /** + * Reset info and warning. + */ public void resetInfoAndWarning() { noInfo = false; noWarning = false; @@ -163,17 +237,29 @@ public void addCleanupTask(final ModelDescription model) { docDelegate.addCleanupTask(model); } + /** + * Checks for error on. + * + * @param objects the objects + * @return true, if successful + */ public boolean hasErrorOn(final EObject... objects) { final List list = Arrays.asList(objects); return StreamEx.of(items()).filter(IS_ERROR).findAny(p -> list.contains(p.getStatement())).isPresent(); } + /** + * Sets the no experiment. + */ public void setNoExperiment() { noExperiment = true; } - public boolean getNoExperiment() { - return noExperiment; - } + /** + * Gets the no experiment. + * + * @return the no experiment + */ + public boolean getNoExperiment() { return noExperiment; } } diff --git a/msi.gama.core/src/msi/gaml/operators/Cast.java b/msi.gama.core/src/msi/gaml/operators/Cast.java index 94873bd54b..8ecde0fc4e 100644 --- a/msi.gama.core/src/msi/gaml/operators/Cast.java +++ b/msi.gama.core/src/msi/gaml/operators/Cast.java @@ -1,9 +1,8 @@ /******************************************************************************************************* * - * msi.gaml.operators.Cast.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and simulation - * platform (v. 1.8.1) + * Cast.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -15,7 +14,6 @@ import msi.gama.kernel.model.IModel; import msi.gama.metamodel.agent.IAgent; import msi.gama.metamodel.shape.GamaPoint; - import msi.gama.metamodel.shape.IShape; import msi.gama.metamodel.topology.ITopology; import msi.gama.precompiler.GamlAnnotations.doc; @@ -62,6 +60,19 @@ @SuppressWarnings ({ "rawtypes" }) public class Cast { + /** + * Checks if is A. + * + * @param scope + * the scope + * @param a + * the a + * @param b + * the b + * @return the boolean + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = { IKeyword.IS }, category = { IOperatorCategory.CASTING }, @@ -88,6 +99,17 @@ public static Boolean isA(final IScope scope, final Object a, final IExpression return type.isAssignableFrom(GamaType.of(a)); } + /** + * Checks if is skill. + * + * @param scope + * the scope + * @param a + * the a + * @param skill + * the skill + * @return the boolean + */ @operator ( value = IKeyword.IS_SKILL, category = { IOperatorCategory.CASTING }, @@ -105,21 +127,51 @@ public static Boolean isSkill(final IScope scope, final Object a, final String s return s.implementsSkill(skill); } + /** + * As type. + * + * @param scope + * the scope + * @param expr + * the expr + * @return the i type + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IType asType(final IScope scope, final IExpression expr) throws GamaRuntimeException { final Object value = expr.value(scope); if (value instanceof String) { final IModel m = scope.getModel(); return m.getDescription().getTypeNamed((String) value); - } else if (value instanceof ISpecies) - return ((ISpecies) value).getDescription().getGamlType(); - else - return expr.getGamlType(); + } + if (value instanceof ISpecies) return ((ISpecies) value).getDescription().getGamlType(); + return expr.getGamlType(); } + /** + * As graph. + * + * @param scope + * the scope + * @param val + * the val + * @return the i graph + */ public static IGraph asGraph(final IScope scope, final Object val) { return GamaGraphType.staticCast(scope, val, null, false); } + /** + * As topology. + * + * @param scope + * the scope + * @param val + * the val + * @return the i topology + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = IKeyword.TOPOLOGY, content_type = IType.GEOMETRY, @@ -147,10 +199,32 @@ public static ITopology asTopology(final IScope scope, final Object val) throws return GamaTopologyType.staticCast(scope, val, false); } + /** + * As agent. + * + * @param scope + * the scope + * @param val + * the val + * @return the i agent + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IAgent asAgent(final IScope scope, final Object val) throws GamaRuntimeException { return (IAgent) Types.AGENT.cast(scope, val, null, false); } + /** + * As. + * + * @param scope + * the scope + * @param val + * the val + * @param type + * the type + * @return the object + */ @operator ( value = IKeyword.AS, type = ITypeProvider.SECOND_DENOTED_TYPE, @@ -169,65 +243,219 @@ public static Object as(final IScope scope, final Object val, final IType type) return type.cast(scope, val, null, false); } + /** + * As bool. + * + * @param scope + * the scope + * @param val + * the val + * @param copy + * the copy + * @return the boolean + */ public static Boolean asBool(final IScope scope, final Object val, final boolean copy) { // copy not passed return GamaBoolType.staticCast(scope, val, null, false); } + /** + * As bool. + * + * @param scope + * the scope + * @param val + * the val + * @return the boolean + */ public static Boolean asBool(final IScope scope, final Object val) { // copy not passed return asBool(scope, val, false); } + /** + * As color. + * + * @param scope + * the scope + * @param val + * the val + * @param copy + * the copy + * @return the gama color + * @throws GamaRuntimeException + * the gama runtime exception + */ public static GamaColor asColor(final IScope scope, final Object val, final boolean copy) throws GamaRuntimeException { // copy not passed return GamaColorType.staticCast(scope, val, null, false); } + /** + * As color. + * + * @param scope + * the scope + * @param val + * the val + * @return the gama color + */ public static GamaColor asColor(final IScope scope, final Object val) { return asColor(scope, val, false); } + /** + * As float. + * + * @param scope + * the scope + * @param val + * the val + * @return the double + */ public static Double asFloat(final IScope scope, final Object val) { return GamaFloatType.staticCast(scope, val, null, false); } + /** + * As geometry. + * + * @param scope + * the scope + * @param s + * the s + * @param copy + * the copy + * @return the i shape + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IShape asGeometry(final IScope scope, final Object s, final boolean copy) throws GamaRuntimeException { return GamaGeometryType.staticCast(scope, s, null, copy); } + /** + * As geometry. + * + * @param scope + * the scope + * @param s + * the s + * @return the i shape + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IShape asGeometry(final IScope scope, final Object s) throws GamaRuntimeException { return asGeometry(scope, s, false); } + /** + * As int. + * + * @param scope + * the scope + * @param val + * the val + * @return the integer + */ public static Integer asInt(final IScope scope, final Object val) { return GamaIntegerType.staticCast(scope, val, null, false); } + /** + * As pair. + * + * @param scope + * the scope + * @param val + * the val + * @param copy + * the copy + * @return the gama pair + * @throws GamaRuntimeException + * the gama runtime exception + */ public static GamaPair asPair(final IScope scope, final Object val, final boolean copy) throws GamaRuntimeException { return GamaPairType.staticCast(scope, val, Types.NO_TYPE, Types.NO_TYPE, copy); } + /** + * As string. + * + * @param scope + * the scope + * @param val + * the val + * @return the string + * @throws GamaRuntimeException + * the gama runtime exception + */ public static String asString(final IScope scope, final Object val) throws GamaRuntimeException { return GamaStringType.staticCast(scope, val, false); } + /** + * As point. + * + * @param scope + * the scope + * @param val + * the val + * @param copy + * the copy + * @return the gama point + */ public static GamaPoint asPoint(final IScope scope, final Object val, final boolean copy) { GamaPoint result = GamaPointType.staticCast(scope, val, copy); return result == null ? null : result; } + /** + * As point. + * + * @param scope + * the scope + * @param val + * the val + * @return the gama point + */ public static GamaPoint asPoint(final IScope scope, final Object val) { return asPoint(scope, val, false); } + /** + * As map. + * + * @param scope + * the scope + * @param val + * the val + * @param copy + * the copy + * @return the i map + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IMap asMap(final IScope scope, final Object val, final boolean copy) throws GamaRuntimeException { return (IMap) Types.MAP.cast(scope, val, null, copy); } + /** + * As int. + * + * @param scope + * the scope + * @param string + * the string + * @param radix + * the radix + * @return the integer + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = "as_int", can_be_const = true, @@ -259,10 +487,32 @@ public static Integer asInt(final IScope scope, final String string, final Integ return GamaIntegerType.staticCast(scope, string, radix, false); } + /** + * As list. + * + * @param scope + * the scope + * @param val + * the val + * @return the i list + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IList asList(final IScope scope, final Object val) throws GamaRuntimeException { return GamaListType.staticCast(scope, val, null, false); } + /** + * List with. + * + * @param scope + * the scope + * @param size + * the size + * @param init + * the init + * @return the i list + */ @operator ( value = "list_with", content_type = ITypeProvider.TYPE_AT_INDEX + 2, @@ -280,10 +530,32 @@ public static IList list_with(final IScope scope, final Integer size, final IExp return GamaListFactory.create(scope, init, size); } + /** + * As matrix. + * + * @param scope + * the scope + * @param val + * the val + * @return the i matrix + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IMatrix asMatrix(final IScope scope, final Object val) throws GamaRuntimeException { return asMatrix(scope, val, null); } + /** + * Matrix with. + * + * @param scope + * the scope + * @param size + * the size + * @param init + * the init + * @return the i matrix + */ @operator ( value = "matrix_with", content_type = ITypeProvider.SECOND_CONTENT_TYPE_OR_TYPE, @@ -297,20 +569,26 @@ public static IMatrix asMatrix(final IScope scope, final Object val) throws Gama @test ("{2,2} matrix_with (1) = matrix([1,1],[1,1])") public static IMatrix matrix_with(final IScope scope, final GamaPoint size, final IExpression init) { if (size == null) throw GamaRuntimeException.error("A nil size is not allowed for matrices", scope); - return GamaMatrixType.with(scope, init, (GamaPoint) size); + return GamaMatrixType.with(scope, init, size); } + /** + * As matrix. + * + * @param scope + * the scope + * @param val + * the val + * @param size + * the size + * @return the i matrix + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = "as_matrix", content_type = ITypeProvider.FIRST_CONTENT_TYPE_OR_TYPE, - can_be_const = true, // AD: - // was - // previously - // true - // -- - // see - // Issue - // 1127 + can_be_const = true, category = { IOperatorCategory.CASTING }, concept = { IConcept.CAST, IConcept.CONTAINER }) @doc ( @@ -328,6 +606,17 @@ public static IMatrix asMatrix(final IScope scope, final Object val, final GamaP return GamaMatrixType.staticCast(scope, val, size, Types.NO_TYPE, false); } + /** + * As species. + * + * @param scope + * the scope + * @param val + * the val + * @return the i species + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = { IKeyword.SPECIES, "species_of" }, content_type = ITypeProvider.TYPE_AT_INDEX + 1, @@ -360,6 +649,13 @@ public static ISpecies asSpecies(final IScope scope, final Object val) throws Ga return (ISpecies) Types.SPECIES.cast(scope, val, null, false); } + /** + * To gaml. + * + * @param val + * the val + * @return the string + */ @operator ( value = "to_gaml", category = { IOperatorCategory.CASTING }, diff --git a/msi.gama.core/src/msi/gaml/operators/Dates.java b/msi.gama.core/src/msi/gaml/operators/Dates.java index 6099a441b3..d8fbeba4e9 100644 --- a/msi.gama.core/src/msi/gaml/operators/Dates.java +++ b/msi.gama.core/src/msi/gaml/operators/Dates.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.operators.Dates.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * Dates.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.operators; @@ -66,20 +66,43 @@ import msi.gaml.types.IType; import ummisco.gama.dev.utils.DEBUG; +/** + * The Class Dates. + */ public class Dates { + /** The Constant ISO_LOCAL_KEY. */ public static final String ISO_LOCAL_KEY = "ISO_LOCAL_DATE_TIME"; + + /** The Constant ISO_OFFSET_KEY. */ public static final String ISO_OFFSET_KEY = "ISO_OFFSET_DATE_TIME"; + + /** The Constant ISO_ZONED_KEY. */ public static final String ISO_ZONED_KEY = "ISO_ZONED_DATE_TIME"; + + /** The Constant ISO_SIMPLE_KEY. */ public static final String ISO_SIMPLE_KEY = "ISO_SIMPLE"; + + /** The Constant CUSTOM_KEY. */ public static final String CUSTOM_KEY = "CUSTOM"; + + /** The default value. */ public static String DEFAULT_VALUE = "CUSTOM"; + + /** The Constant DEFAULT_KEY. */ public static final String DEFAULT_KEY = "DEFAULT"; + + /** The Constant DEFAULT_FORMAT. */ public static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + /** The Constant ISO_SIMPLE_FORMAT. */ public static final String ISO_SIMPLE_FORMAT = "yy-MM-dd HH:mm:ss"; + + /** The Constant DURATION_FORMATTER. */ static final DurationFormatter DURATION_FORMATTER = new DurationFormatter(); - public static HashMap FORMATTERS = new HashMap<>() { + /** The Constant FORMATTERS. */ + public static final HashMap FORMATTERS = new HashMap<>() { { put(DEFAULT_KEY, DateTimeFormatter.ofPattern(DEFAULT_FORMAT)); put(ISO_SIMPLE_KEY, DateTimeFormatter.ofPattern(ISO_SIMPLE_FORMAT)); @@ -90,6 +113,7 @@ public class Dates { } }; + /** The Constant DATES_CUSTOM_FORMATTER. */ public final static Pref DATES_CUSTOM_FORMATTER = GamaPreferences.create("pref_date_custom_formatter", "Custom date pattern (https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#patterns)", DEFAULT_FORMAT, IType.STRING, true).in(GamaPreferences.External.NAME, GamaPreferences.External.DATES) @@ -102,6 +126,7 @@ public class Dates { } }); + /** The Constant DATES_DEFAULT_FORMATTER. */ public final static Pref DATES_DEFAULT_FORMATTER = GamaPreferences .create("pref_date_default_formatter", "Default date pattern for writing dates (i.e. string(date1))", CUSTOM_KEY, IType.STRING, true) @@ -111,10 +136,12 @@ public class Dates { FORMATTERS.put(DEFAULT_KEY, FORMATTERS.get(e)); }); + /** The Constant DATES_STARTING_DATE. */ public final static Pref DATES_STARTING_DATE = GamaPreferences .create("pref_date_starting_date", "Default starting date of models", GamaDateType.EPOCH, IType.DATE, true) .in(GamaPreferences.External.NAME, GamaPreferences.External.DATES); + /** The Constant DATES_TIME_STEP. */ public final static Pref DATES_TIME_STEP = GamaPreferences.create("pref_date_time_step", "Default time step of models", 1d, IType.FLOAT, true) .in(GamaPreferences.External.NAME, GamaPreferences.External.DATES).between(1d, null); @@ -124,15 +151,28 @@ public class Dates { FORMATTERS.put(DEFAULT_KEY, FORMATTERS.get(CUSTOM_KEY)); } + /** The Constant APPROXIMATE_TEMPORAL_QUERY. */ public static final String APPROXIMATE_TEMPORAL_QUERY = IKeyword.INTERNAL_FUNCTION + "_temporal_query"; + /** The model pattern. */ static Pattern model_pattern = Pattern.compile("%[YMNDEhmsz]"); + /** + * Initialize. + */ public static void initialize() { // Only here to load the class and its preferences } + /** + * Approximal query. + * + * @param scope the scope + * @param left the left + * @param right the right + * @return the double + */ @operator ( value = APPROXIMATE_TEMPORAL_QUERY, doc = @doc ("For internal use only"), @@ -142,11 +182,19 @@ public static double approximalQuery(final IScope scope, final IExpression left, final Double arg = Cast.asFloat(scope, left.value(scope)); if (right instanceof TimeUnitConstantExpression) return scope.getClock().getCurrentDate().getDuration(scope, (TimeUnitConstantExpression) right, arg); - else - return 0d; + return 0d; } + /** + * Minus date. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return the double + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { IKeyword.MINUS }, content_type = IType.NONE, @@ -167,6 +215,13 @@ public static double minusDate(final IScope scope, final GamaDate date1, final G return duration.getSeconds(); } + /** + * Every. + * + * @param scope the scope + * @param period the period + * @return the boolean + */ @operator ( value = { "every", "every_cycle" }, category = { IOperatorCategory.SYSTEM }, @@ -186,6 +241,13 @@ public static Boolean every(final IScope scope, final Integer period) { return period > 0 && (time == 0 || time >= period) && time % period == 0; } + /** + * Every. + * + * @param scope the scope + * @param period the period + * @return the boolean + */ @operator ( value = "every", category = { IOperatorCategory.DATE }, @@ -205,6 +267,14 @@ public static Boolean every(final IScope scope, final IExpression period) { return scope.getClock().getStartingDate().isIntervalReached(scope, period); } + /** + * Every. + * + * @param scope the scope + * @param interval the interval + * @param period the period + * @return the i list + */ @operator ( value = "every", category = { IOperatorCategory.DATE }, @@ -221,6 +291,14 @@ public static IList every(final IScope scope, final GamaDateInterval i return interval.step(Cast.asFloat(scope, period.value(scope))); } + /** + * To. + * + * @param scope the scope + * @param start the start + * @param end the end + * @return the i list + */ @operator ( value = "to", category = { IOperatorCategory.DATE }, @@ -241,6 +319,13 @@ public static IList to(final IScope scope, final GamaDate start, final return GamaDateInterval.of(start, end); } + /** + * Since. + * + * @param scope the scope + * @param date the date + * @return true, if successful + */ @operator ( value = { "since", "from" }, category = { IOperatorCategory.DATE }, @@ -260,6 +345,13 @@ public static boolean since(final IScope scope, final GamaDate date) { return scope.getSimulation().getCurrentDate().isGreaterThan(date, false); } + /** + * After. + * + * @param scope the scope + * @param date the date + * @return true, if successful + */ @operator ( value = { "after" }, category = { IOperatorCategory.DATE }, @@ -282,6 +374,13 @@ public static boolean after(final IScope scope, final GamaDate date) { return scope.getSimulation().getCurrentDate().isGreaterThan(date, true); } + /** + * Before. + * + * @param scope the scope + * @param date the date + * @return true, if successful + */ @operator ( value = { "before" }, category = { IOperatorCategory.DATE }, @@ -298,6 +397,13 @@ public static boolean before(final IScope scope, final GamaDate date) { return scope.getSimulation().getCurrentDate().isSmallerThan(date, true); } + /** + * Until. + * + * @param scope the scope + * @param date the date + * @return true, if successful + */ @operator ( value = { "until", "to" }, category = { IOperatorCategory.DATE }, @@ -314,6 +420,14 @@ public static boolean until(final IScope scope, final GamaDate date) { return scope.getSimulation().getCurrentDate().isSmallerThan(date, false); } + /** + * Since. + * + * @param scope the scope + * @param expression the expression + * @param date the date + * @return true, if successful + */ @operator ( value = { "since", "from" }, category = { IOperatorCategory.DATE }, @@ -324,6 +438,14 @@ public static boolean since(final IScope scope, final IExpression expression, fi return since(scope, date) && Cast.asBool(scope, expression.value(scope)); } + /** + * After. + * + * @param scope the scope + * @param expression the expression + * @param date the date + * @return true, if successful + */ @operator ( value = { "after" }, doc = @doc ("Returns true if the first operand is true and the current date is situated strictly after the second operand"), @@ -334,6 +456,14 @@ public static boolean after(final IScope scope, final IExpression expression, fi return after(scope, date) && Cast.asBool(scope, expression.value(scope)); } + /** + * Before. + * + * @param scope the scope + * @param expression the expression + * @param date the date + * @return true, if successful + */ @operator ( value = { "before" }, category = { IOperatorCategory.DATE }, @@ -344,6 +474,14 @@ public static boolean before(final IScope scope, final IExpression expression, f return before(scope, date) && Cast.asBool(scope, expression.value(scope)); } + /** + * Until. + * + * @param scope the scope + * @param expression the expression + * @param date the date + * @return true, if successful + */ @operator ( value = { "until", "to" }, doc = @doc ("Returns true if the first operand is true and the current date is equal to or situated before the second operand"), @@ -354,6 +492,15 @@ public static boolean until(final IScope scope, final IExpression expression, fi return until(scope, date) && Cast.asBool(scope, expression.value(scope)); } + /** + * Between. + * + * @param scope the scope + * @param expression the expression + * @param start the start + * @param stop the stop + * @return true, if successful + */ @operator ( value = { "between" }, category = { IOperatorCategory.DATE }, @@ -365,6 +512,15 @@ public static boolean between(final IScope scope, final IExpression expression, return between(scope, scope.getClock().getCurrentDate(), start, stop) && (boolean) expression.value(scope); } + /** + * Between. + * + * @param scope the scope + * @param date the date + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + */ @operator ( value = { "between" }, category = { IOperatorCategory.DATE }, @@ -386,6 +542,14 @@ public static boolean between(final IScope scope, final GamaDate date, final Gam return date.isGreaterThan(date1, true) && date.isSmallerThan(date2, true); } + /** + * Between. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + */ @operator ( value = { "between" }, category = { IOperatorCategory.DATE }, @@ -402,6 +566,15 @@ public static boolean between(final IScope scope, final GamaDate date1, final Ga && scope.getSimulation().getCurrentDate().isSmallerThan(date2, true); } + /** + * Plus duration. + * + * @param scope the scope + * @param date1 the date 1 + * @param duration the duration + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { IKeyword.PLUS, "plus_seconds", "add_seconds" }, content_type = IType.NONE, @@ -419,6 +592,15 @@ public static GamaDate plusDuration(final IScope scope, final GamaDate date1, fi return date1.plus(duration, SECONDS); } + /** + * Plus duration. + * + * @param scope the scope + * @param date1 the date 1 + * @param duration the duration + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { IKeyword.PLUS }, content_type = IType.NONE, @@ -436,6 +618,15 @@ public static GamaDate plusDuration(final IScope scope, final GamaDate date1, fi return date1.plus(duration * 1000, ChronoUnit.MILLIS); } + /** + * Minus duration. + * + * @param scope the scope + * @param date1 the date 1 + * @param duration the duration + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { IKeyword.MINUS, "minus_seconds", "subtract_seconds" }, content_type = IType.NONE, @@ -454,6 +645,15 @@ public static GamaDate minusDuration(final IScope scope, final GamaDate date1, f return date1.plus(-duration, SECONDS); } + /** + * Minus duration. + * + * @param scope the scope + * @param date1 the date 1 + * @param duration the duration + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { IKeyword.MINUS }, content_type = IType.NONE, @@ -471,6 +671,15 @@ public static GamaDate minusDuration(final IScope scope, final GamaDate date1, f return date1.plus(-duration * 1000, ChronoUnit.MILLIS); } + /** + * Concatain date. + * + * @param scope the scope + * @param date1 the date 1 + * @param text the text + * @return the string + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { IKeyword.PLUS }, content_type = IType.NONE, @@ -487,6 +696,15 @@ public static String ConcatainDate(final IScope scope, final GamaDate date1, fin return date1.toString() + text; } + /** + * Adds the years. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbYears the nb years + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "plus_years", "add_years" }, content_type = IType.NONE, @@ -505,6 +723,15 @@ public static GamaDate addYears(final IScope scope, final GamaDate date1, final } + /** + * Adds the months. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbMonths the nb months + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "plus_months", "add_months" }, content_type = IType.NONE, @@ -523,6 +750,15 @@ public static GamaDate addMonths(final IScope scope, final GamaDate date1, final } + /** + * Adds the weeks. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbWeeks the nb weeks + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "plus_weeks", "add_weeks" }, content_type = IType.NONE, @@ -540,6 +776,15 @@ public static GamaDate addWeeks(final IScope scope, final GamaDate date1, final } + /** + * Adds the days. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbDays the nb days + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "plus_days", "add_days" }, content_type = IType.NONE, @@ -557,6 +802,15 @@ public static GamaDate addDays(final IScope scope, final GamaDate date1, final i } + /** + * Adds the hours. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbHours the nb hours + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "plus_hours", "add_hours" }, content_type = IType.NONE, @@ -577,6 +831,15 @@ public static GamaDate addHours(final IScope scope, final GamaDate date1, final } + /** + * Adds the minutes. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbMinutes the nb minutes + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "plus_minutes", "add_minutes" }, content_type = IType.NONE, @@ -597,6 +860,15 @@ public static GamaDate addMinutes(final IScope scope, final GamaDate date1, fina } + /** + * Subtract years. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbYears the nb years + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "minus_years", "subtract_years" }, content_type = IType.NONE, @@ -614,6 +886,15 @@ public static GamaDate subtractYears(final IScope scope, final GamaDate date1, f } + /** + * Subtract months. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbMonths the nb months + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "minus_months", "subtract_months" }, content_type = IType.NONE, @@ -631,6 +912,15 @@ public static GamaDate subtractMonths(final IScope scope, final GamaDate date1, } + /** + * Subtract weeks. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbWeeks the nb weeks + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "minus_weeks", "subtract_weeks" }, content_type = IType.NONE, @@ -648,6 +938,15 @@ public static GamaDate subtractWeeks(final IScope scope, final GamaDate date1, f } + /** + * Subtract days. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbDays the nb days + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "minus_days", "subtract_days" }, content_type = IType.NONE, @@ -665,6 +964,15 @@ public static GamaDate subtractDays(final IScope scope, final GamaDate date1, fi } + /** + * Subtract hours. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbHours the nb hours + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "minus_hours", "subtract_hours" }, content_type = IType.NONE, @@ -685,6 +993,15 @@ public static GamaDate subtractHours(final IScope scope, final GamaDate date1, f } + /** + * Subtract ms. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbMs the nb ms + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "minus_ms", "subtract_ms" }, content_type = IType.NONE, @@ -704,6 +1021,15 @@ public static GamaDate subtractMs(final IScope scope, final GamaDate date1, fina return date1.plus(-nbMs, ChronoUnit.MILLIS); } + /** + * Adds the ms. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbMs the nb ms + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "plus_ms", "add_ms" }, content_type = IType.NONE, @@ -722,6 +1048,15 @@ public static GamaDate addMs(final IScope scope, final GamaDate date1, final int return date1.plus(nbMs, ChronoUnit.MILLIS); } + /** + * Subtract minutes. + * + * @param scope the scope + * @param date1 the date 1 + * @param nbMinutes the nb minutes + * @return the gama date + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "minus_minutes", "subtract_minutes" }, content_type = IType.NONE, @@ -742,6 +1077,15 @@ public static GamaDate subtractMinutes(final IScope scope, final GamaDate date1, } + /** + * Years between. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return the int + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "years_between" }, content_type = IType.NONE, @@ -758,6 +1102,15 @@ public static int years_between(final IScope scope, final GamaDate date1, final return (int) ChronoUnit.YEARS.between(date1, date2); } + /** + * Milliseconds between. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return the double + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "milliseconds_between" }, content_type = IType.NONE, @@ -774,6 +1127,15 @@ public static double milliseconds_between(final IScope scope, final GamaDate dat return ChronoUnit.MILLIS.between(date1, date2); } + /** + * Months between. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return the int + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "months_between" }, content_type = IType.NONE, @@ -790,6 +1152,15 @@ public static int months_between(final IScope scope, final GamaDate date1, final return (int) ChronoUnit.MONTHS.between(date1, date2); } + /** + * Greater than. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { ">" }, content_type = IType.NONE, @@ -806,6 +1177,15 @@ public static boolean greater_than(final IScope scope, final GamaDate date1, fin return date1.isGreaterThan(date2, true); } + /** + * Greater than or equal. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { ">=" }, content_type = IType.NONE, @@ -822,6 +1202,15 @@ public static boolean greater_than_or_equal(final IScope scope, final GamaDate d return date1.isGreaterThan(date2, false); } + /** + * Smaller than. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "<" }, content_type = IType.NONE, @@ -838,6 +1227,15 @@ public static boolean smaller_than(final IScope scope, final GamaDate date1, fin return date1.isSmallerThan(date2, true); } + /** + * Smaller than or equal. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "<=" }, content_type = IType.NONE, @@ -854,6 +1252,15 @@ public static boolean smaller_than_or_equal(final IScope scope, final GamaDate d return date1.isSmallerThan(date2, false); } + /** + * Equal. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "=" }, content_type = IType.NONE, @@ -870,6 +1277,15 @@ public static boolean equal(final IScope scope, final GamaDate date1, final Gama return date1.equals(date2); } + /** + * Different. + * + * @param scope the scope + * @param date1 the date 1 + * @param date2 the date 2 + * @return true, if successful + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = { "!=" }, content_type = IType.NONE, @@ -886,6 +1302,12 @@ public static boolean different(final IScope scope, final GamaDate date1, final return !date1.equals(date2); } + /** + * Gets the locale. + * + * @param l the l + * @return the locale + */ static Locale getLocale(final String l) { if (l == null) return Locale.getDefault(); final String locale = l.toLowerCase(); @@ -909,11 +1331,25 @@ static Locale getLocale(final String l) { } } + /** + * Gets the formatter key. + * + * @param p the p + * @param locale the locale + * @return the formatter key + */ static String getFormatterKey(final String p, final String locale) { if (locale == null) return p; return p + locale; } + /** + * Gets the formatter. + * + * @param p the p + * @param locale the locale + * @return the formatter + */ public static DateTimeFormatter getFormatter(final String p, final String locale) { final String pattern = p; @@ -991,11 +1427,26 @@ public static DateTimeFormatter getFormatter(final String p, final String locale return result; } + /** + * As duration. + * + * @param d1 the d 1 + * @param d2 the d 2 + * @return the string + */ public static String asDuration(final Temporal d1, final Temporal d2) { final Duration p = Duration.between(d1, d2); return DurationFormatter.format(p); } + /** + * Date. + * + * @param scope the scope + * @param value the value + * @param pattern the pattern + * @return the gama date + */ @operator ( value = "date", can_be_const = true, @@ -1014,6 +1465,15 @@ public static GamaDate date(final IScope scope, final String value, final String return new GamaDate(scope, value, pattern); } + /** + * Date. + * + * @param scope the scope + * @param value the value + * @param pattern the pattern + * @param locale the locale + * @return the gama date + */ @operator ( value = "date", can_be_const = true, @@ -1032,6 +1492,13 @@ public static GamaDate date(final IScope scope, final String value, final String return new GamaDate(scope, value, pattern, locale); } + /** + * Format. + * + * @param time the time + * @param pattern the pattern + * @return the string + */ @operator ( value = "string", can_be_const = true, @@ -1052,6 +1519,14 @@ public static String format(final GamaDate time, final String pattern) { return format(time, pattern, null); } + /** + * Format. + * + * @param time the time + * @param pattern the pattern + * @param locale the locale + * @return the string + */ @operator ( value = "string", can_be_const = true, @@ -1071,21 +1546,51 @@ public static String format(final GamaDate time, final String pattern, final Str return time.toString(pattern, locale); } + /** + * The Class DurationFormatter. + */ static class DurationFormatter implements TemporalAccessor { + + /** The Constant YMDHMS. */ private static final DateTimeFormatter YMDHMS = DateTimeFormatter.ofPattern("u'y' M'm' d'd' HH:mm:ss"); + + /** The Constant MDHMS. */ private static final DateTimeFormatter MDHMS = DateTimeFormatter.ofPattern("M' months' d 'days' HH:mm:ss"); + + /** The Constant M1DHMS. */ private static final DateTimeFormatter M1DHMS = DateTimeFormatter.ofPattern("M' month' d 'days' HH:mm:ss"); + + /** The Constant M1D1HMS. */ private static final DateTimeFormatter M1D1HMS = DateTimeFormatter.ofPattern("M' month' d 'day' HH:mm:ss"); + + /** The Constant DHMS. */ private static final DateTimeFormatter DHMS = DateTimeFormatter.ofPattern("d 'days' HH:mm:ss"); + + /** The Constant D1HMS. */ private static final DateTimeFormatter D1HMS = DateTimeFormatter.ofPattern("d 'day' HH:mm:ss"); + + /** The Constant HMS. */ private static final DateTimeFormatter HMS = DateTimeFormatter.ofPattern("HH:mm:ss"); + /** + * Format. + * + * @param duration the duration + * @return the string + */ static String format(final Duration duration) { return DURATION_FORMATTER.toString(duration); } + /** The temporal. */ private Temporal temporal; + /** + * To string. + * + * @param duration the duration + * @return the string + */ private String toString(final Duration duration) { this.temporal = duration.addTo(Dates.DATES_STARTING_DATE.getValue()) .minus(GamaDateType.DEFAULT_OFFSET_IN_SECONDS.getTotalSeconds(), SECONDS); @@ -1094,24 +1599,25 @@ private String toString(final Duration duration) { return toString(); } + /** + * Gets the formatter. + * + * @return the formatter + */ private DateTimeFormatter getFormatter() { if (getLong(YEAR) > 0) return YMDHMS; final long month = getLong(MONTH_OF_YEAR); final long day = getLong(DAY_OF_MONTH); if (month > 0) { - if (month < 2) { - if (day < 2) - return M1D1HMS; - else - return M1DHMS; - } else - return MDHMS; - } - if (day > 0) { + if (month >= 2) return MDHMS; if (day < 2) - return D1HMS; + return M1D1HMS; else - return DHMS; + return M1DHMS; + } + if (day > 0) { + if (day < 2) return D1HMS; + return DHMS; } return HMS; } @@ -1123,9 +1629,8 @@ public boolean isSupported(final TemporalField field) { @Override public long getLong(final TemporalField field) { - if (field == SECOND_OF_MINUTE) - return temporal.getLong(SECOND_OF_MINUTE); - else if (field == MINUTE_OF_HOUR) + if (field == SECOND_OF_MINUTE) return temporal.getLong(SECOND_OF_MINUTE); + if (field == MINUTE_OF_HOUR) return temporal.getLong(MINUTE_OF_HOUR); else if (field == HOUR_OF_DAY) return temporal.getLong(HOUR_OF_DAY); diff --git a/msi.gama.core/src/msi/gaml/operators/Files.java b/msi.gama.core/src/msi/gaml/operators/Files.java index 9c8d6d1934..79688d5af7 100644 --- a/msi.gama.core/src/msi/gaml/operators/Files.java +++ b/msi.gama.core/src/msi/gaml/operators/Files.java @@ -1,9 +1,8 @@ /******************************************************************************************************* * - * msi.gaml.operators.Files.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * Files.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -14,11 +13,8 @@ import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Path; import java.util.Enumeration; import java.util.Map; import java.util.zip.ZipEntry; @@ -26,7 +22,6 @@ import java.util.zip.ZipOutputStream; import org.apache.commons.compress.utils.IOUtils; -import org.eclipse.core.internal.utils.FileUtil; import msi.gama.common.interfaces.IKeyword; import msi.gama.common.util.FileUtils; @@ -56,9 +51,10 @@ * @todo Description * */ -@SuppressWarnings ({ "rawtypes" }) +@SuppressWarnings ({ "rawtypes", "restriction" }) public class Files { + /** The Constant WRITE. */ public static final String WRITE = "write"; // @operator ( @@ -71,6 +67,17 @@ public class Files { // comment = "The type of container to pass will depend on the type of file (see the management of files in the // documentation). Can be used to copy files since files are considered as containers. For example: save // file('image_copy.png', file('image.png')); will copy image.png to image_copy.png") + /** + * From. + * + * @param scope + * the scope + * @param s + * the s + * @param container + * the container + * @return the i gama file + */ // @no_test public static IGamaFile from(final IScope scope, final String s, final IContainer container) { // WARNING Casting to Modifiable is not safe @@ -98,11 +105,31 @@ public static IGamaFile from(final IScope scope, final String s, final IContaine // value = " // fileT represents the file \"../includes/Stupid_Cell.Data\""), // @example ( // value = " // fileT.contents here contains a matrix storing all the data of the text file") }, + /** + * From. + * + * @param scope + * the scope + * @param s + * the s + * @return the i gama file + * @throws GamaRuntimeException + * the gama runtime exception + */ // see = { "folder", "new_folder" }) public static IGamaFile from(final IScope scope, final String s) throws GamaRuntimeException { return from(scope, s, null); } + /** + * Exist file. + * + * @param scope + * the scope + * @param s + * the s + * @return true, if successful + */ @operator ( value = "file_exists", can_be_const = false, @@ -124,17 +151,24 @@ public static IGamaFile from(final IScope scope, final String s) throws GamaRunt isExecutable = false) }) @no_test public static boolean exist_file(final IScope scope, final String s) { - if (s == null) return false; - if (scope == null) - return false; - else { - final String path = FileUtils.constructAbsoluteFilePath(scope, s, false); - final File f = new File(path); - - return f.exists() && !f.isDirectory(); - } + if (s == null || scope == null) return false; + final String path = FileUtils.constructAbsoluteFilePath(scope, s, false); + final File f = new File(path); + + return f.exists() && !f.isDirectory(); } - + + /** + * Zip files. + * + * @param scope + * the scope + * @param zipfile + * the zipfile + * @param s + * the s + * @return true, if successful + */ @operator ( value = "folder_exists", can_be_const = false, @@ -156,94 +190,116 @@ public static boolean exist_file(final IScope scope, final String s) { isExecutable = false) }) @no_test public static boolean zip_files(final IScope scope, final String zipfile, final IList s) { - if (s == null || s.isEmpty()) return false; - if (scope == null) - return false; - + if (s == null || s.isEmpty() || scope == null) return false; + return true; } - - - private static void extractFolder(IScope scope, String zipFile,String extractFolder) - { - try - { - int BUFFER = 2048; - File file = new File(zipFile); - - ZipFile zip = new ZipFile(file); - String newPath = extractFolder; - - new File(newPath).mkdir(); - Enumeration zipFileEntries = zip.entries(); - - // Process each entry - while (zipFileEntries.hasMoreElements()) - { - // grab a zip file entry - ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); - String currentEntry = entry.getName(); - - File destFile = new File(newPath, currentEntry); - //destFile = new File(newPath, destFile.getName()); - File destinationParent = destFile.getParentFile(); - - // create the parent directory structure if needed - destinationParent.mkdirs(); - - if (!entry.isDirectory()) - { - BufferedInputStream is = new BufferedInputStream(zip - .getInputStream(entry)); - int currentByte; - // establish buffer for writing file - byte data[] = new byte[BUFFER]; - - // write the current file to disk - FileOutputStream fos = new FileOutputStream(destFile); - BufferedOutputStream dest = new BufferedOutputStream(fos, - BUFFER); - - // read and write until last byte is encountered - while ((currentByte = is.read(data, 0, BUFFER)) != -1) { - dest.write(data, 0, currentByte); - } - dest.flush(); - dest.close(); - is.close(); - } - - - } - zip.close(); - } - catch (Exception e) - { - GamaRuntimeException.error("ERROR: "+e.getMessage(), scope); - } + + /** + * Extract folder. + * + * @param scope + * the scope + * @param zipFile + * the zip file + * @param extractFolder + * the extract folder + */ + private static void extractFolder(final IScope scope, final String zipFile, final String extractFolder) { + try { + int BUFFER = 2048; + File file = new File(zipFile); + + try (ZipFile zip = new ZipFile(file)) { + String newPath = extractFolder; + + new File(newPath).mkdir(); + Enumeration zipFileEntries = zip.entries(); + + // Process each entry + while (zipFileEntries.hasMoreElements()) { + // grab a zip file entry + ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); + String currentEntry = entry.getName(); + + File destFile = new File(newPath, currentEntry); + // destFile = new File(newPath, destFile.getName()); + File destinationParent = destFile.getParentFile(); + + // create the parent directory structure if needed + destinationParent.mkdirs(); + + if (!entry.isDirectory()) { + try (BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry))) { + int currentByte; + // establish buffer for writing file + byte data[] = new byte[BUFFER]; + + try (// write the current file to disk + FileOutputStream fos = new FileOutputStream(destFile)) { + try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER)) { + // read and write until last byte is encountered + while ((currentByte = is.read(data, 0, BUFFER)) != -1) { + dest.write(data, 0, currentByte); + } + dest.flush(); + } + } + } + } + + } + } + } catch (Exception e) { + GamaRuntimeException.error("ERROR: " + e.getMessage(), scope); + } } - private static void addFolderToZip(File folderOrFile, ZipOutputStream zip, String baseName) throws IOException { + + /** + * Adds the folder to zip. + * + * @param folderOrFile + * the folder or file + * @param zip + * the zip + * @param baseName + * the base name + * @throws IOException + * Signals that an I/O exception has occurred. + */ + private static void addFolderToZip(final File folderOrFile, final ZipOutputStream zip, final String baseName) + throws IOException { File[] files; if (folderOrFile.isDirectory()) { - files = folderOrFile.listFiles(); - } else { - files = new File[1]; - files[0] = folderOrFile; - } - for (File file : files) { - if (file.isDirectory()) { - addFolderToZip(file, zip,baseName); - } else { - String name = file.getAbsolutePath().substring(baseName.length());; - ZipEntry zipEntry = new ZipEntry(name); - zip.putNextEntry(zipEntry); - IOUtils.copy(new FileInputStream(file), zip); - zip.closeEntry(); - } - } + files = folderOrFile.listFiles(); + if (files == null) return; + } else { + files = new File[1]; + files[0] = folderOrFile; + } + for (File file : files) { + if (file.isDirectory()) { + addFolderToZip(file, zip, baseName); + } else { + String name = file.getAbsolutePath().substring(baseName.length()); + ZipEntry zipEntry = new ZipEntry(name); + zip.putNextEntry(zipEntry); + IOUtils.copy(new FileInputStream(file), zip); + zip.closeEntry(); + } + } } - + + /** + * Delete. + * + * @param scope + * the scope + * @param source + * the source + * @return true, if successful + */ @operator ( value = "delete_file", can_be_const = false, @@ -253,38 +309,44 @@ private static void addFolderToZip(File folderOrFile, ZipOutputStream zip, Strin value = "delete a file or a folder", examples = { @example ( value = "bool delete_file_ok <- delete_file([\"../includes/my_folder\"];", - isExecutable = false)}) + isExecutable = false) }) @no_test public static boolean delete(final IScope scope, final String source) { - if (source == null ) return false; - if (scope == null) - return false; - else { - final String pathSource = FileUtils.constructAbsoluteFilePath(scope, source, false); - File file = new File(pathSource); - if (file.isDirectory() ) { - deleteDir(file); - }else { - return file.delete(); - } - return !exist_folder(scope, source); - } + if (source == null || scope == null) return false; + final String pathSource = FileUtils.constructAbsoluteFilePath(scope, source, false); + File file = new File(pathSource); + if (!file.isDirectory()) return file.delete(); + deleteDir(file); + return !exist_folder(scope, source); } - - static void deleteDir(File file) { + + /** + * Delete dir. + * + * @param file + * the file + */ + static void deleteDir(final File file) { if (file.isDirectory()) { File[] contents = file.listFiles(); - if (contents != null) { - for (File f : contents) { - if (! java.nio.file.Files.isSymbolicLink(f.toPath())) { - deleteDir(f); - } - } - } + if (contents != null) { + for (File f : contents) { if (!java.nio.file.Files.isSymbolicLink(f.toPath())) { deleteDir(f); } } + } } file.delete(); } - + + /** + * Unzip. + * + * @param scope + * the scope + * @param source + * the source + * @param destination + * the destination + * @return true, if successful + */ @operator ( value = "unzip", can_be_const = false, @@ -294,20 +356,28 @@ static void deleteDir(File file) { value = "Unzip a given zip file into a given folder. Returns true if the file is well unzipped", examples = { @example ( value = "bool unzip_ok <- unzip([\"../includes/my_folder\"], \"folder.zip\";", - isExecutable = false)}) + isExecutable = false) }) @no_test public static boolean unzip(final IScope scope, final String source, final String destination) { - if (source == null || !exist_file(scope, source) || destination == null ) return false; - if (scope == null) - return false; - else { - final String pathDestination = FileUtils.constructAbsoluteFilePath(scope, destination, false); - final String pathSource = FileUtils.constructAbsoluteFilePath(scope, source, false); - - extractFolder(scope,pathSource,pathDestination); - return true; - } + if (source == null || !exist_file(scope, source) || destination == null || scope == null) return false; + final String pathDestination = FileUtils.constructAbsoluteFilePath(scope, destination, false); + final String pathSource = FileUtils.constructAbsoluteFilePath(scope, source, false); + + extractFolder(scope, pathSource, pathDestination); + return true; } + + /** + * Zip. + * + * @param scope + * the scope + * @param sources + * the sources + * @param destination + * the destination + * @return true, if successful + */ @operator ( value = "zip", can_be_const = false, @@ -317,31 +387,35 @@ public static boolean unzip(final IScope scope, final String source, final Strin value = "Zip a given list of files or folders. Returns true if the files are well zipped", examples = { @example ( value = "bool zip_ok <- zip([\"../includes/my_folder\"], \"folder.zip\";", - isExecutable = false)}) + isExecutable = false) }) @no_test public static boolean zip(final IScope scope, final IList sources, final String destination) { - if (sources == null ||sources.isEmpty() || destination == null) return false; - if (scope == null) - return false; - else { - final String pathDestination = FileUtils.constructAbsoluteFilePath(scope, destination, false); - try (FileOutputStream fos = new FileOutputStream(pathDestination)){ - ZipOutputStream zip = new ZipOutputStream( new BufferedOutputStream(fos)); + if (sources == null || sources.isEmpty() || destination == null || scope == null) return false; + final String pathDestination = FileUtils.constructAbsoluteFilePath(scope, destination, false); + try (FileOutputStream fos = new FileOutputStream(pathDestination)) { + try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(fos))) { for (String source : sources) { final String pathSource = FileUtils.constructAbsoluteFilePath(scope, source, false); File f = new File(pathSource); - addFolderToZip(f,zip, f.getParentFile().getAbsolutePath()); + addFolderToZip(f, zip, f.getParentFile().getAbsolutePath()); } - - zip.close(); - } catch (IOException e) { - GamaRuntimeException.error(e.getMessage(), scope); - } - return true; + + } + } catch (IOException e) { + GamaRuntimeException.error(e.getMessage(), scope); } + return true; } - - + + /** + * Exist folder. + * + * @param scope + * the scope + * @param s + * the s + * @return true, if successful + */ @operator ( value = "folder_exists", can_be_const = false, @@ -363,17 +437,24 @@ public static boolean zip(final IScope scope, final IList sources, final isExecutable = false) }) @no_test public static boolean exist_folder(final IScope scope, final String s) { - if (s == null) return false; - if (scope == null) - return false; - else { - final String path = FileUtils.constructAbsoluteFilePath(scope, s, false); - final File f = new File(path); - - return f.exists() && f.isDirectory(); - } + if (s == null || scope == null) return false; + final String path = FileUtils.constructAbsoluteFilePath(scope, s, false); + final File f = new File(path); + + return f.exists() && f.isDirectory(); } + /** + * Folder file. + * + * @param scope + * the scope + * @param s + * the s + * @return the i gama file + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = IKeyword.FOLDER, can_be_const = false, @@ -399,11 +480,35 @@ public static IGamaFile folderFile(final IScope scope, final String s) throws Ga return new GamaFolderFile(scope, s); } + /** + * Folder file. + * + * @param scope + * the scope + * @param s + * the s + * @param modify + * the modify + * @return the i gama file + * @throws GamaRuntimeException + * the gama runtime exception + */ public static IGamaFile folderFile(final IScope scope, final String s, final boolean modify) throws GamaRuntimeException { return new GamaFolderFile(scope, s, modify); } + /** + * Writable. + * + * @param scope + * the scope + * @param s + * the s + * @param writable + * the writable + * @return the i gama file + */ @operator ( value = "writable", category = IOperatorCategory.FILE, @@ -458,6 +563,19 @@ public static Object opRead(final IScope scope, final String s) throws GamaRunti return opRead(scope, scope.getAgent(), s); } + /** + * Op read. + * + * @param scope + * the scope + * @param g + * the g + * @param s + * the s + * @return the object + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = "get", category = IOperatorCategory.CONTAINER, @@ -481,6 +599,19 @@ public static Object opRead(final IScope scope, final IAgent g, final String s) return g.get(scope, s); } + /** + * Op read. + * + * @param scope + * the scope + * @param g + * the g + * @param s + * the s + * @return the object + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = "get", category = IOperatorCategory.FILE, @@ -503,6 +634,17 @@ public static Object opRead(final IScope scope, final IShape g, final String s) return ((GamaShape) g.getGeometry()).getAttribute(s); } + /** + * New folder. + * + * @param scope + * the scope + * @param folder + * the folder + * @return the i gama file + * @throws GamaRuntimeException + * the gama runtime exception + */ @operator ( value = { "new_folder" }, index_type = IType.INT, diff --git a/msi.gama.core/src/msi/gaml/operators/Random.java b/msi.gama.core/src/msi/gaml/operators/Random.java index c37c8c7f44..af4d9d1e53 100644 --- a/msi.gama.core/src/msi/gaml/operators/Random.java +++ b/msi.gama.core/src/msi/gaml/operators/Random.java @@ -1,18 +1,17 @@ /******************************************************************************************************* * - * msi.gaml.operators.Random.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * Random.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.operators; import msi.gama.common.util.RandomUtils; import msi.gama.metamodel.shape.GamaPoint; - import msi.gama.precompiler.GamlAnnotations.doc; import msi.gama.precompiler.GamlAnnotations.example; import msi.gama.precompiler.GamlAnnotations.no_test; @@ -45,12 +44,25 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class Random { + /** + * Random. + * + * @param scope the scope + * @return the random utils + */ public static RandomUtils RANDOM(final IScope scope) { RandomUtils r = scope.getRandom(); if (r == null) { r = new RandomUtils(); } return r; } + /** + * Op T gauss. + * + * @param scope the scope + * @param p the p + * @return the double + */ @operator ( value = { "truncated_gauss", "TGauss" }, category = { IOperatorCategory.RANDOM }, @@ -70,6 +82,13 @@ public static Double opTGauss(final IScope scope, final GamaPoint p) { return opTGauss(scope, GamaListFactory.wrap(Types.FLOAT, p.x, p.y)); } + /** + * Op T gauss. + * + * @param scope the scope + * @param list the list + * @return the double + */ @operator ( value = { "truncated_gauss", "TGauss" }, category = { IOperatorCategory.RANDOM }, @@ -109,6 +128,13 @@ public static Double opTGauss(final IScope scope, final IList list) { } + /** + * Op gauss. + * + * @param scope the scope + * @param point the point + * @return the double + */ @operator ( value = { "gauss", "gauss_rnd" }, category = { IOperatorCategory.RANDOM }, @@ -130,6 +156,14 @@ public static Double opGauss(final IScope scope, final GamaPoint point) { return RANDOM(scope).createGaussian(mean, sd); } + /** + * Op gauss. + * + * @param scope the scope + * @param mean the mean + * @param sd the sd + * @return the double + */ @operator ( value = { "gauss", "gauss_rnd" }, category = { IOperatorCategory.RANDOM }, @@ -149,6 +183,16 @@ public static Double opGauss(final IScope scope, final double mean, final double return RANDOM(scope).createGaussian(mean, sd); } + /** + * Op gauss. + * + * @param scope the scope + * @param min the min + * @param max the max + * @param skew the skew + * @param bias the bias + * @return the double + */ @operator ( value = "skew_gauss", category = { IOperatorCategory.RANDOM }, @@ -172,6 +216,13 @@ public static Double opGauss(final IScope scope, final double min, final double return mid + range * (biasFactor / (biasFactor + Math.exp(-unitGaussian / skew)) - 0.5); } + /** + * Op poisson. + * + * @param scope the scope + * @param mean the mean + * @return the integer + */ @operator ( value = "poisson", category = { IOperatorCategory.RANDOM }, @@ -190,6 +241,14 @@ public static Integer opPoisson(final IScope scope, final Double mean) { return RANDOM(scope).createPoisson(mean); } + /** + * Op binomial. + * + * @param scope the scope + * @param n the n + * @param p the p + * @return the integer + */ @operator ( value = "binomial", category = { IOperatorCategory.RANDOM }, @@ -208,6 +267,13 @@ public static Integer opBinomial(final IScope scope, final Integer n, final Doub return RANDOM(scope).createBinomial(n, p); } + /** + * Op shuffle. + * + * @param scope the scope + * @param target the target + * @return the i list + */ @operator ( value = "shuffle", content_type = ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, @@ -241,6 +307,14 @@ public static IList opShuffle(final IScope scope, final IContainer target) { // scope.getAgentScope().getPopulationFor(target).getAgentsList()); // } + /** + * Op shuffle. + * + * @param scope the scope + * @param target the target + * @return the i matrix + * @throws GamaRuntimeException the gama runtime exception + */ @operator ( value = "shuffle", content_type = ITypeProvider.CONTENT_TYPE_AT_INDEX + 1, @@ -258,6 +332,13 @@ public static IMatrix opShuffle(final IScope scope, final IMatrix target) throws return matrix2; } + /** + * Op shuffle. + * + * @param scope the scope + * @param target the target + * @return the string + */ @operator ( value = "shuffle", content_type = IType.STRING, @@ -274,6 +355,13 @@ public static String opShuffle(final IScope scope, final String target) { return RANDOM(scope).shuffle(target); } + /** + * Op rnd. + * + * @param scope the scope + * @param max the max + * @return the integer + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -294,6 +382,14 @@ public static Integer opRnd(final IScope scope, final Integer max) { return opRnd(scope, 0, max); } + /** + * Op rnd. + * + * @param scope the scope + * @param min the min + * @param max the max + * @return the integer + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -312,6 +408,15 @@ public static Integer opRnd(final IScope scope, final Integer min, final Integer return r.between(min, max); } + /** + * Op rnd. + * + * @param scope the scope + * @param min the min + * @param max the max + * @param step the step + * @return the integer + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -330,6 +435,14 @@ public static Integer opRnd(final IScope scope, final Integer min, final Integer return r.between(min, max, step); } + /** + * Op rnd. + * + * @param scope the scope + * @param min the min + * @param max the max + * @return the double + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -348,6 +461,15 @@ public static Double opRnd(final IScope scope, final Double min, final Double ma return r.between(min, max); } + /** + * Op rnd. + * + * @param scope the scope + * @param min the min + * @param max the max + * @param step the step + * @return the double + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -366,6 +488,14 @@ public static Double opRnd(final IScope scope, final Double min, final Double ma return r.between(min, max, step); } + /** + * Op rnd. + * + * @param scope the scope + * @param min the min + * @param max the max + * @return the gama point + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -386,6 +516,15 @@ public static GamaPoint opRnd(final IScope scope, final GamaPoint min, final Gam return new GamaPoint(x, y, z); } + /** + * Op rnd. + * + * @param scope the scope + * @param min the min + * @param max the max + * @param step the step + * @return the gama point + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -406,8 +545,16 @@ public static GamaPoint opRnd(final IScope scope, final GamaPoint min, final Gam return new GamaPoint(x, y, z); } + /** The null point. */ static GamaPoint NULL_POINT = new GamaPoint(0, 0, 0); + /** + * Op rnd. + * + * @param scope the scope + * @param max the max + * @return the gama point + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -426,6 +573,13 @@ public static GamaPoint opRnd(final IScope scope, final GamaPoint max) { return opRnd(scope, NULL_POINT, max); } + /** + * Op rnd. + * + * @param scope the scope + * @param max the max + * @return the double + */ @operator ( value = "rnd", category = { IOperatorCategory.RANDOM }, @@ -444,6 +598,13 @@ public static Double opRnd(final IScope scope, final Double max) { return opRnd(scope, 0.0, max); } + /** + * Op flip. + * + * @param scope the scope + * @param probability the probability + * @return the boolean + */ @operator ( value = "flip", category = { IOperatorCategory.RANDOM }, @@ -462,6 +623,13 @@ public static Boolean opFlip(final IScope scope, final Double probability) { return probability > RANDOM(scope).between(0., 1.); } + /** + * Op rnd choice. + * + * @param scope the scope + * @param distribution the distribution + * @return the integer + */ @operator ( value = "rnd_choice", concept = { IConcept.RANDOM }) @@ -501,6 +669,14 @@ public static Integer opRndChoice(final IScope scope, final IList distribution) return -1; } + /** + * Op rnd coice. + * + * @param the generic type + * @param scope the scope + * @param distribution the distribution + * @return the t + */ @operator ( value = "rnd_choice", concept = { IConcept.RANDOM }, @@ -543,6 +719,15 @@ public static T opRndCoice(final IScope scope, final IMap distribution throw GamaRuntimeException.create(new RuntimeException("Malformed distribution"), scope); } + /** + * Op sample. + * + * @param scope the scope + * @param x the x + * @param nb the nb + * @param replacement the replacement + * @return the i list + */ @operator ( value = "sample", type = ITypeProvider.TYPE_AT_INDEX + 1, @@ -572,6 +757,16 @@ public static IList opSample(final IScope scope, final IList x, final int nb, fi return result; } + /** + * Op sample. + * + * @param scope the scope + * @param x the x + * @param nb the nb + * @param replacement the replacement + * @param weights the weights + * @return the i list + */ @operator ( value = "sample", type = ITypeProvider.TYPE_AT_INDEX + 1, @@ -624,12 +819,25 @@ public static IList opSample(final IScope scope, final IList x, final int nb, fi // return SimplexNoise.noise(x, y, biais); // } + /** + * Generate terrain. + * + * @param scope the scope + * @param seed the seed + * @param width the width + * @param height the height + * @param details the details + * @param smoothness the smoothness + * @param scattering the scattering + * @return the i field + */ @operator ( value = "generate_terrain") @doc ("This operator allows to generate a pseudo-terrain using a simplex noise generator. Its usage is kept simple: it takes first a seed (random or not), then the dimensions " + "(width and height) of the field to generate, then a level (between 0 and 1) of details (which actually determines the number of passes to make)" + ", then the value (between 0 and 1) of smoothess, with 0 being completely rought and 1 super smooth, and finally the value (between 0 and 1) of " + "scattering, with 0 building maps in 'one piece' and 1 completely scattered ones.") + @no_test public static IField generateTerrain(final IScope scope, final int seed, final int width, final int height, final double details, final double smoothness, final double scattering) { @@ -664,9 +872,7 @@ public static IField generateTerrain(final IScope scope, final int seed, final i layerWeight *= roughness; } - for (int x = 0; x < totalNoise.length; x++) { - totalNoise[x] /= weightSum; - } + for (int x = 0; x < totalNoise.length; x++) { totalNoise[x] /= weightSum; } return result; } diff --git a/msi.gama.core/src/msi/gaml/operators/Spatial.java b/msi.gama.core/src/msi/gaml/operators/Spatial.java index 442b463eb5..c19d6822f0 100644 --- a/msi.gama.core/src/msi/gaml/operators/Spatial.java +++ b/msi.gama.core/src/msi/gaml/operators/Spatial.java @@ -1,11 +1,12 @@ /******************************************************************************************************* * - * Spatial.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * Spatial.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.operators; @@ -4499,7 +4500,8 @@ public static IList split_lines(final IScope scope, final IContainer) scope.getVarValue("proba_edges"); } moveToNextLocAlongPathSimplified(scope, agent, graph, dist, probaDeplacement); - return; + return true; } final Object bounds = scope.getArg(IKeyword.BOUNDS, IType.NONE); if (bounds != null) { @@ -382,8 +565,18 @@ public void primMoveRandomly(final IScope scope) throws GamaRuntimeException { } } + return true; } + /** + * Prim move forward. + * + * @param scope + * the scope + * @return the i path + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = "move", args = { @arg ( @@ -435,6 +628,15 @@ public IPath primMoveForward(final IScope scope) throws GamaRuntimeException { return null; } + /** + * Prim follow. + * + * @param scope + * the scope + * @return the i path + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = "follow", args = { @arg ( @@ -484,6 +686,15 @@ public IPath primFollow(final IScope scope) throws GamaRuntimeException { return null; } + /** + * Prim goto. + * + * @param scope + * the scope + * @return the i path + * @throws GamaRuntimeException + * the gama runtime exception + */ @action ( name = "goto", args = { @arg ( @@ -621,6 +832,12 @@ public IPath primGoto(final IScope scope) throws GamaRuntimeException { return null; } + /** + * Not moving. + * + * @param agent + * the agent + */ private void notMoving(final IAgent agent) { setRealSpeed(agent, 0.0); agent.setAttribute("current_edge", null); @@ -703,6 +920,17 @@ protected IList initMoveAlongPath3D(final IAgent agent, final IPath path, final return initVals; } + /** + * Inits the move along path. + * + * @param agent + * the agent + * @param path + * the path + * @param cl + * the cl + * @return the i list + */ protected IList initMoveAlongPath(final IAgent agent, final IPath path, final GamaPoint cl) { GamaPoint currentLocation = cl; try (final Collector.AsList initVals = Collector.getList()) { @@ -744,7 +972,7 @@ protected IList initMoveAlongPath(final IAgent agent, final IPath path, final Ga currentLocation = new GamaPoint(currentLocation); indexSegment = indexOf(points, currentLocation) + 1; } else { - currentLocation = (GamaPoint) Punctal._closest_point_to(currentLocation, line); + currentLocation = Punctal._closest_point_to(currentLocation, line); if (points.length >= 3) { distanceS = Double.MAX_VALUE; final int nbSp = points.length; @@ -774,7 +1002,7 @@ protected IList initMoveAlongPath(final IAgent agent, final IPath path, final Ga falseTarget = new GamaPoint(end); endIndexSegment = indexOf(points, end) + 1; } else { - falseTarget = (GamaPoint) Punctal._closest_point_to(end, lineEnd); + falseTarget = Punctal._closest_point_to(end, lineEnd); endIndexSegment = 1; if (points.length >= 3) { double distanceT = Double.MAX_VALUE; @@ -804,6 +1032,19 @@ protected IList initMoveAlongPath(final IAgent agent, final IPath path, final Ga } } + /** + * Inits the move along path. + * + * @param scope + * the scope + * @param agent + * the agent + * @param graph + * the graph + * @param currentLoc + * the current loc + * @return the i list + */ @SuppressWarnings ("null") protected IList initMoveAlongPath(final IScope scope, final IAgent agent, final GamaSpatialGraph graph, final GamaPoint currentLoc) { @@ -866,7 +1107,7 @@ protected IList initMoveAlongPath(final IScope scope, final IAgent agent, final currentLocation = new GamaPoint(currentLocation); indexSegment = indexOf(points, currentLocation) + 1; } else { - currentLocation = (GamaPoint) Punctal._closest_point_to(currentLocation, line); + currentLocation = Punctal._closest_point_to(currentLocation, line); if (points.length >= 3) { Double distanceS = Double.MAX_VALUE; for (int i = 0; i < points.length - 1; i++) { @@ -895,6 +1136,20 @@ protected IList initMoveAlongPath(final IScope scope, final IAgent agent, final } } + /** + * Move to next loc along path simplified. + * + * @param scope + * the scope + * @param agent + * the agent + * @param graph + * the graph + * @param d + * the d + * @param probaEdge + * the proba edge + */ public void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent agent, final GamaSpatialGraph graph, final double d, final IMap probaEdge) { GamaPoint currentLocation = agent.getLocation().copy(scope); @@ -912,9 +1167,7 @@ public void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent ag if (!graph.isDirected() && inverse == 1) { final int si = coords.length; final Coordinate coords2[] = new Coordinate[si]; - for (int i = 0; i < coords.length; i++) { - coords2[i] = coords[si - 1 - i]; - } + for (int i = 0; i < coords.length; i++) { coords2[i] = coords[si - 1 - i]; } coords = coords2; } @@ -934,47 +1187,8 @@ public void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent ag currentLocation.setLocation(newX, newY, newZ); distance = 0; break; - } else if (distance > dist) { - currentLocation = pt; - travelledDist += dis; - - distance = distance - dist; - indexSegment++; - if (j == coords.length - 1) { - IShape node = (IShape) graph.getEdgeTarget(edge); - if (!graph.isDirected() && !node.getLocation().equals(currentLocation)) { - node = (IShape) graph.getEdgeSource(edge); - } - final List nextRoads = new ArrayList( - graph.isDirected() ? graph.outgoingEdgesOf(node) : graph.edgesOf(node)); - if (nextRoads.isEmpty()) { - distance = 0; - break; - } - if (nextRoads.size() == 1) { edge = nextRoads.get(0); } - if (nextRoads.size() > 1) { - if (probaEdge == null || probaEdge.isEmpty()) { - edge = nextRoads.get(scope.getRandom().between(0, nextRoads.size() - 1)); - } else { - final IList distribution = GamaListFactory.create(Types.FLOAT); - for (final IShape r : nextRoads) { - final Double val = (Double) probaEdge.get(r); - distribution.add(val == null ? 0.0 : val); - } - edge = nextRoads.get(Random.opRndChoice(scope, distribution)); - } - } - index = graph.getEdges().indexOf(edge); - if (!graph.isDirected()) { - if (currentLocation.equals(graph.getEdgeSource(edge))) { - inverse = 0; - } else { - inverse = 1; - } - } - indexSegment = 0; - } - } else { + } + if (distance <= dist) { currentLocation = pt; travelledDist += dis; distance = 0; @@ -985,6 +1199,45 @@ public void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent ag } break; } + currentLocation = pt; + travelledDist += dis; + + distance = distance - dist; + indexSegment++; + if (j == coords.length - 1) { + IShape node = (IShape) graph.getEdgeTarget(edge); + if (!graph.isDirected() && !node.getLocation().equals(currentLocation)) { + node = (IShape) graph.getEdgeSource(edge); + } + final List nextRoads = new ArrayList( + graph.isDirected() ? graph.outgoingEdgesOf(node) : graph.edgesOf(node)); + if (nextRoads.isEmpty()) { + distance = 0; + break; + } + if (nextRoads.size() == 1) { edge = nextRoads.get(0); } + if (nextRoads.size() > 1) { + if (probaEdge == null || probaEdge.isEmpty()) { + edge = nextRoads.get(scope.getRandom().between(0, nextRoads.size() - 1)); + } else { + final IList distribution = GamaListFactory.create(Types.FLOAT); + for (final IShape r : nextRoads) { + final Double val = (Double) probaEdge.get(r); + distribution.add(val == null ? 0.0 : val); + } + edge = nextRoads.get(Random.opRndChoice(scope, distribution)); + } + } + index = graph.getEdges().indexOf(edge); + if (!graph.isDirected()) { + if (currentLocation.equals(graph.getEdgeSource(edge))) { + inverse = 0; + } else { + inverse = 1; + } + } + indexSegment = 0; + } } if (distance == 0) { break; } indexSegment = 1; @@ -1000,6 +1253,20 @@ public void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent ag setHeading(agent, computedHeading); } + /** + * Move to next loc along path simplified. + * + * @param scope + * the scope + * @param agent + * the agent + * @param path + * the path + * @param d + * the d + * @param weigths + * the weigths + */ private void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent agent, final IPath path, final double d, final IMap weigths) { GamaPoint currentLocation = agent.getLocation().copy(scope); @@ -1050,13 +1317,8 @@ private void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent a currentLocation.setLocation(newX, newY, newZ); distance = 0; break; - } else if (distance > dist) { - currentLocation = pt; - travelledDist += dis; - distance = distance - dist; - if (i == nb - 1 && j == endIndexSegment) { break; } - indexSegment++; - } else { + } + if (distance <= dist) { currentLocation = pt; distance = 0; travelledDist += dis; @@ -1068,6 +1330,11 @@ private void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent a } break; } + currentLocation = pt; + travelledDist += dis; + distance = distance - dist; + if (i == nb - 1 && j == endIndexSegment) { break; } + indexSegment++; } if (distance == 0) { break; } indexSegment = 1; @@ -1089,12 +1356,38 @@ private void moveToNextLocAlongPathSimplified(final IScope scope, final IAgent a } + /** + * Compute weigth. + * + * @param graph + * the graph + * @param path + * the path + * @param line + * the line + * @return the double + */ protected double computeWeigth(final IGraph graph, final IPath path, final IShape line) { if (graph == null) return 1.0; final IShape realShape = path.getRealObject(line); return realShape == null ? 1 : graph.getEdgeWeight(realShape) / realShape.getGeometry().getPerimeter(); } + /** + * Move to next loc along path. + * + * @param scope + * the scope + * @param agent + * the agent + * @param path + * the path + * @param d + * the d + * @param weigths + * the weigths + * @return the i path + */ private IPath moveToNextLocAlongPath(final IScope scope, final IAgent agent, final IPath path, final double d, final IMap weigths) { final GamaPoint startLocation = agent.getLocation().copy(scope); @@ -1162,21 +1455,8 @@ private IPath moveToNextLocAlongPath(final IScope scope, final IAgent agent, fin segments.add(gl); break; - } else if (distance > dist) { - travelledDist += dis; - final IShape gl = GamaGeometryType.buildLine(currentLocation, pt); - final IShape sh = path.getRealObject(line); - if (sh != null) { - final IAgent a = sh.getAgent(); - if (a != null) { agents.put(gl, a); } - } - segments.add(gl); - - currentLocation = pt; - distance = distance - dist; - if (i == nb - 1 && j == endIndexSegment) { break; } - indexSegment++; - } else { + } + if (distance <= dist) { travelledDist += dis; final IShape gl = GamaGeometryType.buildLine(currentLocation, pt); if (path.getRealObject(line) != null) { @@ -1196,6 +1476,19 @@ private IPath moveToNextLocAlongPath(final IScope scope, final IAgent agent, fin } break; } + travelledDist += dis; + final IShape gl = GamaGeometryType.buildLine(currentLocation, pt); + final IShape sh = path.getRealObject(line); + if (sh != null) { + final IAgent a = sh.getAgent(); + if (a != null) { agents.put(gl, a); } + } + segments.add(gl); + + currentLocation = pt; + distance = distance - dist; + if (i == nb - 1 && j == endIndexSegment) { break; } + indexSegment++; } if (distance == 0) { break; } indexSegment = 1; @@ -1222,6 +1515,19 @@ private IPath moveToNextLocAlongPath(final IScope scope, final IAgent agent, fin return followedPath; } + /** + * Compute location forward. + * + * @param scope + * the scope + * @param dist + * the dist + * @param loc + * the loc + * @param geom + * the geom + * @return the gama point + */ protected GamaPoint computeLocationForward(final IScope scope, final double dist, final GamaPoint loc, final IShape geom) { final IList pts = GamaListFactory.create(Types.POINT); diff --git a/msi.gama.core/src/msi/gaml/skills/MovingSkill3D.java b/msi.gama.core/src/msi/gaml/skills/MovingSkill3D.java index c9bb73fb0b..f516ffcaaa 100644 --- a/msi.gama.core/src/msi/gaml/skills/MovingSkill3D.java +++ b/msi.gama.core/src/msi/gaml/skills/MovingSkill3D.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.skills.MovingSkill3D.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * MovingSkill3D.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.skills; @@ -83,6 +83,12 @@ public GamaPoint getDestination(final IAgent agent) { return topology.getDestination3D(actualLocation, getHeading(agent), getPitch(agent), dist, false); } + /** + * Gets the pitch. + * + * @param agent the agent + * @return the pitch + */ @getter (IKeyword.PITCH) public Double getPitch(final IAgent agent) { Double p = (Double) agent.getAttribute(IKeyword.PITCH); @@ -93,11 +99,23 @@ public Double getPitch(final IAgent agent) { return Maths.checkHeading(p); } + /** + * Sets the pitch. + * + * @param agent the agent + * @param newPitch the new pitch + */ @setter (IKeyword.PITCH) public void setPitch(final IAgent agent, final double newPitch) { agent.setAttribute(IKeyword.PITCH, newPitch); } + /** + * Gets the roll. + * + * @param agent the agent + * @return the roll + */ @getter (IKeyword.ROLL) public Double getRoll(final IAgent agent) { Double r = (Double) agent.getAttribute(IKeyword.ROLL); @@ -108,17 +126,39 @@ public Double getRoll(final IAgent agent) { return Maths.checkHeading(r); } + /** + * Sets the roll. + * + * @param agent the agent + * @param newRoll the new roll + */ @setter (IKeyword.ROLL) public void setRoll(final IAgent agent, final Double newRoll) { agent.setAttribute(IKeyword.ROLL, newRoll); } + /** + * Compute pitch from amplitude. + * + * @param scope the scope + * @param agent the agent + * @return the double + * @throws GamaRuntimeException the gama runtime exception + */ protected double computePitchFromAmplitude(final IScope scope, final IAgent agent) throws GamaRuntimeException { final int ampl = scope.hasArg("amplitude") ? scope.getIntArg("amplitude") : 359; setPitch(agent, getPitch(agent) + scope.getRandom().between(-ampl / 2, ampl / 2)); return getPitch(agent); } + /** + * Compute pitch. + * + * @param scope the scope + * @param agent the agent + * @return the double + * @throws GamaRuntimeException the gama runtime exception + */ protected double computePitch(final IScope scope, final IAgent agent) throws GamaRuntimeException { final Integer pitch = scope.hasArg(IKeyword.PITCH) ? scope.getIntArg(IKeyword.PITCH) : null; if (pitch != null) { setPitch(agent, pitch); } @@ -181,7 +221,7 @@ public IPath primMoveForward(final IScope scope) throws GamaRuntimeException { } @Override - public void primMoveRandomly(final IScope scope) throws GamaRuntimeException { + public boolean primMoveRandomly(final IScope scope) throws GamaRuntimeException { final IAgent agent = getCurrentAgent(scope); final GamaPoint location = agent.getLocation(); @@ -202,7 +242,7 @@ public void primMoveRandomly(final IScope scope) throws GamaRuntimeException { probaDeplacement = (IMap) scope.getVarValue("proba_edges"); } moveToNextLocAlongPathSimplified(scope, agent, graph, dist, probaDeplacement); - return; + return true; } final Object bounds = scope.getArg(IKeyword.BOUNDS, IType.NONE); if (bounds != null) { @@ -241,6 +281,7 @@ public void primMoveRandomly(final IScope scope) throws GamaRuntimeException { setHeading(agent, heading); setPitch(agent, pitch); } + return true; } @Override diff --git a/msi.gama.core/src/msi/gaml/statements/AspectStatement.java b/msi.gama.core/src/msi/gaml/statements/AspectStatement.java index 0bd4dc8716..0444fe3179 100644 --- a/msi.gama.core/src/msi/gaml/statements/AspectStatement.java +++ b/msi.gama.core/src/msi/gaml/statements/AspectStatement.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * AspectStatement.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * AspectStatement.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.statements; @@ -106,10 +106,10 @@ public class AspectStatement extends AbstractStatementSequence { }; /** The border color. */ - public static GamaColor borderColor = GamaColor.getInt(Color.black.getRGB()); + public static final GamaColor borderColor = GamaColor.getInt(Color.black.getRGB()); /** The default aspect. */ - public static IExecutable DEFAULT_ASPECT = sc -> { + public static final IExecutable DEFAULT_ASPECT = sc -> { if (!sc.isGraphics()) return null; IGraphicsScope scope = (IGraphicsScope) sc; final IAgent agent = scope.getAgent(); diff --git a/msi.gama.core/src/msi/gaml/statements/CaptureStatement.java b/msi.gama.core/src/msi/gaml/statements/CaptureStatement.java index 2e67ba84a3..05f1173879 100644 --- a/msi.gama.core/src/msi/gaml/statements/CaptureStatement.java +++ b/msi.gama.core/src/msi/gaml/statements/CaptureStatement.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * CaptureStatement.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * CaptureStatement.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.statements; @@ -151,10 +151,10 @@ public void validate(final StatementDescription cd) { /** The target. */ private IExpression target; - + /** The return string. */ private final String returnString; - + /** The micro species name. */ private String microSpeciesName = null; @@ -164,7 +164,8 @@ public void validate(final StatementDescription cd) { /** * Instantiates a new capture statement. * - * @param desc the desc + * @param desc + * the desc */ public CaptureStatement(final IDescription desc) { super(desc); @@ -231,7 +232,7 @@ public Object privateExecuteIn(final IScope scope) throws GamaRuntimeException { microAgents.clear(); // scope.addVarWithValue(IKeyword.MYSELF, macroAgent); - if (!capturedAgents.isEmpty() && (sequence != null && !sequence.isEmpty())) { + if (!capturedAgents.isEmpty() && sequence != null && !sequence.isEmpty()) { for (final IAgent capturedA : capturedAgents) { if (!scope.execute(sequence, capturedA, null).passed()) { break; } } @@ -268,8 +269,8 @@ public Object privateExecuteIn(final IScope scope) throws GamaRuntimeException { } raStr.remove(raStr.size() - 1); - final StringBuilder raB = new StringBuilder(); - for (final String s : raStr) { raB.append(s); } + // final StringBuilder raB = new StringBuilder(); + // for (final String s : raStr) { raB.append(s); } if (microSpeciesName != null) throw GamaRuntimeException.error( macroAgent.getName() + " can't capture " + raStr.toString() + " as " + microSpeciesName + " agent", diff --git a/msi.gama.core/src/msi/gaml/statements/CreateStatement.java b/msi.gama.core/src/msi/gaml/statements/CreateStatement.java index d0470f0737..c6bb026ab7 100644 --- a/msi.gama.core/src/msi/gaml/statements/CreateStatement.java +++ b/msi.gama.core/src/msi/gaml/statements/CreateStatement.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * CreateStatement.java, in msi.gama.core, is part of the source code of the - * GAMA modeling and simulation platform (v.1.8.2). + * CreateStatement.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.statements; @@ -122,7 +122,8 @@ name = AS, type = { IType.SPECIES }, optional = true, - doc = @doc ("")), + internal = true, + doc = @doc ("optionally indicates a species into which to cast the created agents.")), @facet ( name = WITH, type = { IType.MAP }, @@ -226,7 +227,7 @@ value = "}", isExecutable = false) }), @usage ( - value = "Desprecated uses: ", + value = "Deprecated uses: ", examples = { @example ( value = "// Simple syntax", isExecutable = false), @@ -351,19 +352,19 @@ protected void serializeArgs(final SymbolDescription s, final StringBuilder sb, /** The init. */ // private final ThreadLocal init = new ThreadLocal(); private Arguments init; - + /** The header. */ private final IExpression from, number, species, header; - + /** The returns. */ private final String returns; - + /** The sequence. */ private final RemoteSequence sequence; - + /** The delegates. */ static List delegates = new ArrayList<>(); - + /** The delegate types. */ static List delegateTypes = new ArrayList<>(); @@ -379,7 +380,8 @@ public static void addDelegate(final ICreateDelegate delegate) { /** * Removes the delegate. * - * @param cd the cd + * @param cd + * the cd */ public static void removeDelegate(final ICreateDelegate cd) { delegates.remove(cd); @@ -388,7 +390,8 @@ public static void removeDelegate(final ICreateDelegate cd) { /** * Instantiates a new creates the statement. * - * @param desc the desc + * @param desc + * the desc */ public CreateStatement(final IDescription desc) { super(desc); @@ -416,7 +419,8 @@ public void enterScope(final IScope scope) { /** * Find population. * - * @param scope the scope + * @param scope + * the scope * @return the i population */ IPopulation findPopulation(final IScope scope) { @@ -494,7 +498,8 @@ private void checkPopulationValidity(final IPopulation pop, final IScope scope) /** * Gets the source. * - * @param scope the scope + * @param scope + * the scope * @return the source */ private Object getSource(final IScope scope) { @@ -508,9 +513,12 @@ private Object getSource(final IScope scope) { /** * Creates the agents. * - * @param scope the scope - * @param population the population - * @param inits the inits + * @param scope + * the scope + * @param population + * the population + * @param inits + * the inits * @return the i list */ private IList createAgents(final IScope scope, final IPopulation population, @@ -564,8 +572,10 @@ private IList createAgents(final IScope scope, final IPopulati /** * Fill with user init. * - * @param scope the scope - * @param values the values + * @param scope + * the scope + * @param values + * the values */ // TODO Call it before calling the ICreateDelegate createFrom method ! public void fillWithUserInit(final IScope scope, final Map values) { diff --git a/msi.gama.core/src/msi/gaml/statements/SaveStatement.java b/msi.gama.core/src/msi/gaml/statements/SaveStatement.java index c85a25fcd3..f0788e2be8 100644 --- a/msi.gama.core/src/msi/gaml/statements/SaveStatement.java +++ b/msi.gama.core/src/msi/gaml/statements/SaveStatement.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.statements.SaveStatement.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * SaveStatement.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -123,6 +123,9 @@ import msi.gaml.types.IType; import msi.gaml.types.Types; +/** + * The Class SaveStatement. + */ @symbol ( name = IKeyword.SAVE, kind = ISymbolKind.SINGLE_STATEMENT, @@ -221,6 +224,9 @@ @SuppressWarnings ({ "rawtypes" }) public class SaveStatement extends AbstractStatementSequence implements IStatement.WithArgs { + /** + * The Class SaveValidator. + */ public static class SaveValidator implements IDescriptionValidator { /** @@ -293,10 +299,21 @@ public void validate(final StatementDescription description) { } + /** The with facet. */ private Arguments withFacet; + + /** The attributes facet. */ private final IExpression attributesFacet; + + /** The header. */ private final IExpression crsCode, item, file, rewriteExpr, header; + /** + * Instantiates a new save statement. + * + * @param desc + * the desc + */ public SaveStatement(final IDescription desc) { super(desc); crsCode = desc.getFacetExpr("crs"); @@ -307,6 +324,13 @@ public SaveStatement(final IDescription desc) { attributesFacet = getFacet(IKeyword.ATTRIBUTES); } + /** + * Should overwrite. + * + * @param scope + * the scope + * @return true, if successful + */ private boolean shouldOverwrite(final IScope scope) { if (rewriteExpr == null) return true; return Cast.asBool(scope, rewriteExpr.value(scope)); @@ -320,15 +344,13 @@ public Object privateExecuteIn(final IScope scope) throws GamaRuntimeException { if (item == null) return null; // First case: we have a file as item; if (file == null) { - if (Types.FILE.isAssignableFrom(item.getGamlType())) { - final IGamaFile file = (IGamaFile) item.value(scope); - if (file != null) { - // Passes directly the facets of the statement, like crs, etc. - file.save(scope, description.getFacets()); - } - return file; - } else - return null; + if (!Types.FILE.isAssignableFrom(item.getGamlType())) return null; + final IGamaFile file = (IGamaFile) item.value(scope); + if (file != null) { + // Passes directly the facets of the statement, like crs, etc. + file.save(scope, description.getFacets()); + } + return file; } final String typeExp = getLiteral(IKeyword.TYPE); // Second case: a filename is indicated but not the type. In that case, @@ -414,12 +436,11 @@ public Object privateExecuteIn(final IScope scope) throws GamaRuntimeException { } break; default: - if (getAvailableWriters().contains(type)) { - final IGraph g = Cast.asGraph(scope, item); - if (g == null) return null; - this.saveGraph(g, fileToSave, type, scope); - } else + if (!getAvailableWriters().contains(type)) throw GamaRuntimeException.error("Format is not recognized ('" + type + "')", scope); + final IGraph g = Cast.asGraph(scope, item); + if (g == null) return null; + this.saveGraph(g, fileToSave, type, scope); } } catch (final GamaRuntimeException e) { throw e; @@ -430,12 +451,28 @@ public Object privateExecuteIn(final IScope scope) throws GamaRuntimeException { return Cast.asString(scope, file.value(scope)); } + /** + * Creates the parents. + * + * @param outputFile + * the output file + */ private static void createParents(final File outputFile) { final File parent = outputFile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } } + /** + * Save asc. + * + * @param field + * the field + * @param f + * the f + * @param scope + * the scope + */ public void saveAsc(final GamaField field, final File f, final IScope scope) { if (field == null || field.isEmpty(scope)) return; if (f.exists()) { f.delete(); } @@ -467,15 +504,23 @@ public void saveAsc(final GamaField field, final File f, final IScope scope) { for (int i = 0; i < nbRows; i++) { StringBuilder val = new StringBuilder(); - for (int j = 0; j < nbCols; j++) { - val.append(field.get(scope, j, i)).append(" "); - } + for (int j = 0; j < nbCols; j++) { val.append(field.get(scope, j, i)).append(" "); } fw.write(val.append(Strings.LN).toString()); } fw.close(); } catch (final IOException e) {} } + /** + * Save asc. + * + * @param species + * the species + * @param f + * the f + * @param scope + * the scope + */ public void saveAsc(final ISpecies species, final File f, final IScope scope) { if (f.exists()) { f.delete(); } @@ -508,9 +553,7 @@ public void saveAsc(final ISpecies species, final File f, final IScope scope) { for (int i = 0; i < nbRows; i++) { StringBuilder val = new StringBuilder(); - for (int j = 0; j < nbCols; j++) { - val.append(gp.getGridValue(j, i)).append(" "); - } + for (int j = 0; j < nbCols; j++) { val.append(gp.getGridValue(j, i)).append(" "); } fw.write(val.append(Strings.LN).toString()); } fw.close(); @@ -518,6 +561,18 @@ public void saveAsc(final ISpecies species, final File f, final IScope scope) { } + /** + * Save raster image. + * + * @param species + * the species + * @param p + * the p + * @param scope + * the scope + * @param toGeotiff + * the to geotiff + */ public void saveRasterImage(final ISpecies species, final String p, final IScope scope, final boolean toGeotiff) { String path = p; @@ -597,6 +652,15 @@ public void saveRasterImage(final ISpecies species, final String p, final IScope } } + /** + * Save prj. + * + * @param scope + * the scope + * @param path + * the path + * @return the coordinate reference system + */ CoordinateReferenceSystem savePrj(final IScope scope, final String path) { CoordinateReferenceSystem crs = null; final boolean nullProjection = scope.getSimulation().getProjectionFactory().getWorld() == null; @@ -618,6 +682,18 @@ CoordinateReferenceSystem savePrj(final IScope scope, final String path) { } + /** + * Save raster image. + * + * @param field + * the field + * @param p + * the p + * @param scope + * the scope + * @param toGeotiff + * the to geotiff + */ public void saveRasterImage(final GamaField field, final String p, final IScope scope, final boolean toGeotiff) { if (field == null || field.isEmpty(scope)) return; @@ -707,6 +783,17 @@ public void saveRasterImage(final GamaField field, final String p, final IScope // Inspired by the code of public GridCoverage2D create(final CharSequence name, final float[][] matrix, final // Envelope envelope) + /** + * Creates the coverage byte from float. + * + * @param name + * the name + * @param matrix + * the matrix + * @param envelope + * the envelope + * @return the grid coverage 2 D + */ // from org.geotools.coverage.grid.GridCoverageFactory public static GridCoverage2D createCoverageByteFromFloat(final CharSequence name, final float[][] matrix, final Envelope envelope) { @@ -723,19 +810,20 @@ public static GridCoverage2D createCoverageByteFromFloat(final CharSequence name for (int j = 0; j < height; j++) { int i = 0; final float[] row = matrix[j]; - if (row != null) { - for (; i < row.length; i++) { - raster.setSample(i, j, 0, (byte) Math.round(row[i])); - } - } - for (; i < width; i++) { - raster.setSample(i, j, 0, (byte) 255); - } + if (row != null) { for (; i < row.length; i++) { raster.setSample(i, j, 0, (byte) Math.round(row[i])); } } + for (; i < width; i++) { raster.setSample(i, j, 0, (byte) 255); } } return new GridCoverageFactory().create(name, raster, envelope); } + /** + * Gets the geometry type. + * + * @param agents + * the agents + * @return the geometry type + */ public static String getGeometryType(final List agents) { String geomType = ""; boolean isLine = false; @@ -744,26 +832,21 @@ public static String getGeometryType(final List agents) { if (geom != null && geom.getInnerGeometry() != null) { if (geom.getInnerGeometry().getNumGeometries() > 1) { Geometry g2 = geometryCollectionToSimpleManagement(geom.getInnerGeometry()); - if (! isLine && g2.getGeometryN(0).getClass() == Point.class) { + if (!isLine && g2.getGeometryN(0).getClass() == Point.class) { geomType = Point.class.getSimpleName(); } else if (g2.getGeometryN(0).getClass() == LineString.class) { geomType = LineString.class.getSimpleName(); - } else if (g2.getGeometryN(0).getClass() == Polygon.class) { - return Polygon.class.getSimpleName(); - } - + } else if (g2.getGeometryN(0).getClass() == Polygon.class) return Polygon.class.getSimpleName(); + } else { String geomType_tmp = geom.getInnerGeometry().getClass().getSimpleName(); - if (geom.getInnerGeometry() instanceof Polygon) { - return geomType_tmp; - } else if (! isLine) { - if (geom.getInnerGeometry() instanceof LineString) { - isLine = true; - } + if (geom.getInnerGeometry() instanceof Polygon) return geomType_tmp; + if (!isLine) { + if (geom.getInnerGeometry() instanceof LineString) { isLine = true; } geomType = geomType_tmp; - + } - + } } } @@ -771,11 +854,37 @@ public static String getGeometryType(final List agents) { return geomType; } + /** + * Save graph. + * + * @param g + * the g + * @param f + * the f + * @param type + * the type + * @param scope + * the scope + */ public void saveGraph(final IGraph g, final File f, final String type, final IScope scope) { - GraphExporter exp = GraphExporters.getGraphWriter(type); + GraphExporter exp = GraphExporters.getGraphWriter(type); if (exp != null) { exp.exportGraph(g, f.getAbsoluteFile()); } } + /** + * Save shape. + * + * @param agents + * the agents + * @param f + * the f + * @param scope + * the scope + * @param geoJson + * the geo json + * @throws GamaRuntimeException + * the gama runtime exception + */ public void saveShape(final IList agents, final File f, final IScope scope, final boolean geoJson) throws GamaRuntimeException { final StringBuilder specs = new StringBuilder(agents.size() * 20); @@ -802,7 +911,7 @@ public void saveShape(final IList agents, final File f, final // } final IProjection proj = defineProjection(scope, f); if (!geoJson) { - saveShapeFile(scope, f, agents, specs.toString(),geomType, attributes, proj); + saveShapeFile(scope, f, agents, specs.toString(), geomType, attributes, proj); } else { saveGeoJSonFile(scope, f, agents, specs.toString(), geomType, attributes, proj); } @@ -814,6 +923,15 @@ public void saveShape(final IList agents, final File f, final } + /** + * Define projection. + * + * @param scope + * the scope + * @param f + * the f + * @return the i projection + */ public IProjection defineProjection(final IScope scope, final File f) { String code = null; if (crsCode != null) { @@ -861,8 +979,8 @@ public IProjection defineProjection(final IScope scope, final File f) { if (cs.length == 2) { final Double val = Double.parseDouble(cs[1]); return new SimpleScalingProjection(val); - } else - return null; + } + return null; } try { @@ -877,6 +995,20 @@ public IProjection defineProjection(final IScope scope, final File f) { return gis; } + /** + * Save text. + * + * @param type + * the type + * @param fileTxt + * the file txt + * @param header + * the header + * @param scope + * the scope + * @throws GamaRuntimeException + * the gama runtime exception + */ public void saveText(final String type, final File fileTxt, final boolean header, final IScope scope) throws GamaRuntimeException { try (FileWriter fw = new FileWriter(fileTxt, true)) { @@ -901,9 +1033,7 @@ public void saveText(final String type, final File fileTxt, final boolean header attributeNames.removeAll(NON_SAVEABLE_ATTRIBUTE_NAMES); if (header) { fw.write("cycle;name;location.x;location.y;location.z"); - for (final String v : attributeNames) { - fw.write(";" + v); - } + for (final String v : attributeNames) { fw.write(";" + v); } fw.write(Strings.LN); } for (final Object obj : values) { @@ -955,6 +1085,13 @@ public void saveText(final String type, final File fileTxt, final boolean header } + /** + * To clean string. + * + * @param o + * the o + * @return the string + */ public String toCleanString(final Object o) { String val = Cast.toGaml(o).replace(';', ','); if (val.startsWith("'") && val.endsWith("'") || val.startsWith("\"") && val.endsWith("\"")) { @@ -969,6 +1106,13 @@ public String toCleanString(final Object o) { return val; } + /** + * Type. + * + * @param var + * the var + * @return the string + */ public String type(final ITyped var) { switch (var.getGamlType().id()) { case IType.BOOL: @@ -982,9 +1126,24 @@ public String type(final ITyped var) { } } + /** The Constant NON_SAVEABLE_ATTRIBUTE_NAMES. */ private static final Set NON_SAVEABLE_ATTRIBUTE_NAMES = new HashSet<>(Arrays.asList(IKeyword.PEERS, IKeyword.LOCATION, IKeyword.HOST, IKeyword.AGENTS, IKeyword.MEMBERS, IKeyword.SHAPE)); + /** + * Compute inits from with facet. + * + * @param scope + * the scope + * @param withFacet + * the with facet + * @param values + * the values + * @param species + * the species + * @throws GamaRuntimeException + * the gama runtime exception + */ private void computeInitsFromWithFacet(final IScope scope, final Arguments withFacet, final Map values, final SpeciesDescription species) throws GamaRuntimeException { if (species == null) return; @@ -1000,6 +1159,18 @@ private void computeInitsFromWithFacet(final IScope scope, final Arguments withF } } + /** + * Compute inits from attributes facet. + * + * @param scope + * the scope + * @param values + * the values + * @param species + * the species + * @throws GamaRuntimeException + * the gama runtime exception + */ private void computeInitsFromAttributesFacet(final IScope scope, final Map values, final SpeciesDescription species) throws GamaRuntimeException { if (attributesFacet instanceof MapExpression) { @@ -1009,7 +1180,7 @@ private void computeInitsFromAttributesFacet(final IScope scope, final Map names = + @SuppressWarnings ("unchecked") final List names = GamaListFactory.create(scope, Types.STRING, Cast.asList(scope, attributesFacet.value(scope))); if (species != null) { names.forEach(n -> values.put(n, @@ -1021,6 +1192,13 @@ private void computeInitsFromAttributesFacet(final IScope scope, final Map attributeValues) { final List values = new ArrayList<>(); @@ -1110,10 +1303,35 @@ public static boolean buildFeature(final IScope scope, final SimpleFeature ff, f return true; } + /** + * Save geo J son file. + * + * @param scope + * the scope + * @param f + * the f + * @param agents + * the agents + * @param specs + * the specs + * @param geomType + * the geom type + * @param attributes + * the attributes + * @param gis + * the gis + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws SchemaException + * the schema exception + * @throws GamaRuntimeException + * the gama runtime exception + */ // AD 2/1/16 Replace IAgent by IShape so as to be able to save geometries public static void saveGeoJSonFile(final IScope scope, final File f, final List agents, - /* final String featureTypeName, */final String specs, final String geomType, final Map attributes, - final IProjection gis) throws IOException, SchemaException, GamaRuntimeException { + /* final String featureTypeName, */final String specs, final String geomType, + final Map attributes, final IProjection gis) + throws IOException, SchemaException, GamaRuntimeException { // AD 11/02/15 Added to allow saving to new directories if (agents == null || agents.isEmpty()) return; @@ -1135,15 +1353,40 @@ public static void saveGeoJSonFile(final IScope scope, final File f, final List< featureCollection.add(ff); } - final FeatureJSON io = new FeatureJSON(new GeometryJSON(20)); - io.writeFeatureCollection(featureCollection, f.getAbsolutePath()); + final FeatureJSON io = new FeatureJSON(new GeometryJSON(20)); + io.writeFeatureCollection(featureCollection, f.getAbsolutePath()); } + /** + * Save shape file. + * + * @param scope + * the scope + * @param f + * the f + * @param agents + * the agents + * @param specs + * the specs + * @param geomType + * the geom type + * @param attributes + * the attributes + * @param gis + * the gis + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws SchemaException + * the schema exception + * @throws GamaRuntimeException + * the gama runtime exception + */ // AD 2/1/16 Replace IAgent by IShape so as to be able to save geometries public static void saveShapeFile(final IScope scope, final File f, final List agents, - /* final String featureTypeName, */final String specs, final String geomType, final Map attributes, - final IProjection gis) throws IOException, SchemaException, GamaRuntimeException { + /* final String featureTypeName, */final String specs, final String geomType, + final Map attributes, final IProjection gis) + throws IOException, SchemaException, GamaRuntimeException { // AD 11/02/15 Added to allow saving to new directories if (agents == null || agents.isEmpty()) return; @@ -1155,28 +1398,29 @@ public static void saveShapeFile(final IScope scope, final File f, final List attributeValues = attributes == null ? Collections.EMPTY_LIST : attributes.values(); - + for (final IShape ag : agents) { if (ag.getGeometries().size() > 1) { ag.setInnerGeometry(geometryCollectionToSimpleManagement(ag.getInnerGeometry())); } - if ((isPolygon && (ag.getInnerGeometry() instanceof Polygon || ag.getInnerGeometry() instanceof MultiPolygon)) || - (isLine && ag.getGeometry().isLine()) || - (isPoint && ag.getGeometry().isPoint()) - ) - { + if (isPolygon + && (ag.getInnerGeometry() instanceof Polygon || ag.getInnerGeometry() instanceof MultiPolygon) + || isLine && ag.getGeometry().isLine() || isPoint && ag.getGeometry().isPoint()) { final SimpleFeature ff = (SimpleFeature) fw.next(); final boolean ok = buildFeature(scope, ff, ag, gis, attributeValues); if (!ok) { break; } } - + } fw.close(); // Writes the prj file @@ -1200,78 +1444,88 @@ public static void saveShapeFile(final IScope scope, final File f, final List polys = new ArrayList<>(); List lines = new ArrayList<>(); List points = new ArrayList<>(); - + for (int i = 0; i < nb; i++) { final Geometry g = ((GeometryCollection) gg).getGeometryN(i); - if ((g instanceof Polygon)) { polys.add((Polygon) g);} - else if ((g instanceof LineString)) {lines.add((LineString) g); } - else if ((g instanceof Point)) { points.add((Point) g); } + if (g instanceof Polygon) { + polys.add((Polygon) g); + } else if (g instanceof LineString) { + lines.add((LineString) g); + } else if (g instanceof Point) { points.add((Point) g); } } if (!polys.isEmpty()) { if (polys.size() == 1) return polys.get(0); Polygon[] ps = new Polygon[polys.size()]; - for (int i = 0; i < ps.length; i++) ps[i] = polys.get(i); - + for (int i = 0; i < ps.length; i++) { ps[i] = polys.get(i); } + return GeometryUtils.GEOMETRY_FACTORY.createMultiPolygon(ps); } if (!lines.isEmpty()) { if (lines.size() == 1) return lines.get(0); LineString[] ps = new LineString[lines.size()]; - for (int i = 0; i < ps.length; i++) ps[i] = lines.get(i); + for (int i = 0; i < ps.length; i++) { ps[i] = lines.get(i); } return GeometryUtils.GEOMETRY_FACTORY.createMultiLineString(ps); } if (!points.isEmpty()) { if (points.size() == 1) return points.get(0); - + Point[] ps = new Point[points.size()]; - for (int i = 0; i < ps.length; i++) ps[i] = points.get(i); + for (int i = 0; i < ps.length; i++) { ps[i] = points.get(i); } return GeometryUtils.GEOMETRY_FACTORY.createMultiPoint(ps); } } return gg; } + /** + * Geometry collection management. + * + * @param gg + * the gg + * @return the geometry + */ private static Geometry geometryCollectionManagement(final Geometry gg) { if (gg instanceof GeometryCollection) { boolean isMultiPolygon = true; boolean isMultiPoint = true; boolean isMultiLine = true; final int nb = ((GeometryCollection) gg).getNumGeometries(); - + for (int i = 0; i < nb; i++) { final Geometry g = ((GeometryCollection) gg).getGeometryN(i); if (!(g instanceof Polygon)) { isMultiPolygon = false; } if (!(g instanceof LineString)) { isMultiLine = false; } if (!(g instanceof Point)) { isMultiPoint = false; } } - + if (isMultiPolygon) { final Polygon[] polygons = new Polygon[nb]; - for (int i = 0; i < nb; i++) { - polygons[i] = (Polygon) ((GeometryCollection) gg).getGeometryN(i); - } + for (int i = 0; i < nb; i++) { polygons[i] = (Polygon) ((GeometryCollection) gg).getGeometryN(i); } return GeometryUtils.GEOMETRY_FACTORY.createMultiPolygon(polygons); } if (isMultiLine) { final LineString[] lines = new LineString[nb]; - for (int i = 0; i < nb; i++) { - lines[i] = (LineString) ((GeometryCollection) gg).getGeometryN(i); - } + for (int i = 0; i < nb; i++) { lines[i] = (LineString) ((GeometryCollection) gg).getGeometryN(i); } return GeometryUtils.GEOMETRY_FACTORY.createMultiLineString(lines); } if (isMultiPoint) { final Point[] points = new Point[nb]; - for (int i = 0; i < nb; i++) { - points[i] = (Point) ((GeometryCollection) gg).getGeometryN(i); - } + for (int i = 0; i < nb; i++) { points[i] = (Point) ((GeometryCollection) gg).getGeometryN(i); } return GeometryUtils.GEOMETRY_FACTORY.createMultiPoint(points); } } @@ -1279,9 +1533,7 @@ private static Geometry geometryCollectionManagement(final Geometry gg) { } @Override - public void setFormalArgs(final Arguments args) { - withFacet = args; - } + public void setFormalArgs(final Arguments args) { withFacet = args; } @Override public void setRuntimeArgs(final IScope scope, final Arguments args) { diff --git a/msi.gama.core/src/msi/gaml/statements/draw/ShapeDrawingAttributes.java b/msi.gama.core/src/msi/gaml/statements/draw/ShapeDrawingAttributes.java index 5253715f6a..6548f9312e 100644 --- a/msi.gama.core/src/msi/gaml/statements/draw/ShapeDrawingAttributes.java +++ b/msi.gama.core/src/msi/gaml/statements/draw/ShapeDrawingAttributes.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.statements.draw.ShapeDrawingAttributes.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * ShapeDrawingAttributes.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.statements.draw; @@ -21,9 +21,29 @@ import msi.gama.util.GamaMaterial; import msi.gama.util.file.GamaImageFile; +/** + * The Class ShapeDrawingAttributes. + */ @SuppressWarnings ({ "rawtypes", "unchecked" }) public class ShapeDrawingAttributes extends FileDrawingAttributes { + /** + * Instantiates a new shape drawing attributes. + * + * @param size the size + * @param depth the depth + * @param rotation the rotation + * @param location the location + * @param empty the empty + * @param color the color + * @param border the border + * @param textures the textures + * @param material the material + * @param agent the agent + * @param type the type + * @param lineWidth the line width + * @param lighting the lighting + */ public ShapeDrawingAttributes(final Scaling3D size, final Double depth, final AxisAngle rotation, final GamaPoint location, final Boolean empty, final GamaColor color, /* final List colors, */ final GamaColor border, final List textures, final GamaMaterial material, final IAgent agent, @@ -37,6 +57,14 @@ public ShapeDrawingAttributes(final Scaling3D size, final Double depth, final Ax // setColors(colors); } + /** + * Instantiates a new shape drawing attributes. + * + * @param location the location + * @param color the color + * @param border the border + * @param type the type + */ public ShapeDrawingAttributes(final GamaPoint location, final GamaColor color, final GamaColor border, final IShape.Type type) { super(null, null, location, color, border, null, null, false, null); @@ -49,15 +77,34 @@ public ShapeDrawingAttributes(final GamaPoint location, final GamaColor color, f // null); } + /** + * Instantiates a new shape drawing attributes. + * + * @param shape the shape + * @param agent the agent + * @param color the color + * @param border the border + */ public ShapeDrawingAttributes(final IShape shape, final IAgent agent, final GamaColor color, final GamaColor border) { this(shape, agent, color, border, shape.getGeometricalType(), null, shape.getDepth()); } + /** + * Instantiates a new shape drawing attributes. + * + * @param shape the shape + * @param agent the agent + * @param color the color + * @param border the border + * @param type the type + * @param lineWidth the line width + * @param depth the depth + */ public ShapeDrawingAttributes(final IShape shape, final IAgent agent, final GamaColor color, final GamaColor border, final IShape.Type type, final Double lineWidth, final Double depth) { - this(null, depth, null, (GamaPoint) shape.getLocation(), color == null, color, /* null, */ border, null, null, - agent, type, lineWidth, null); + this(null, depth, null, shape.getLocation(), color == null, color, /* null, */ border, null, null, agent, type, + lineWidth, null); } } \ No newline at end of file diff --git a/msi.gama.core/src/msi/gaml/statements/test/AbstractSummary.java b/msi.gama.core/src/msi/gaml/statements/test/AbstractSummary.java index dce1ad373f..7cfd639c8c 100644 --- a/msi.gama.core/src/msi/gaml/statements/test/AbstractSummary.java +++ b/msi.gama.core/src/msi/gaml/statements/test/AbstractSummary.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.statements.test.AbstractSummary.java, in plugin msi.gama.core, is part of the source code of the GAMA - * modeling and simulation platform (v. 1.8.1) + * AbstractSummary.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -17,14 +17,34 @@ import msi.gama.common.preferences.GamaPreferences; import msi.gama.util.GamaColor; import one.util.streamex.StreamEx; +import ummisco.gama.dev.utils.COUNTER; +/** + * The Class AbstractSummary. + * + * @param + * the generic type + */ public abstract class AbstractSummary> { - private static int COUNT = 0; + + /** The uri. */ private final URI uri; + + /** The title. */ private final String title; - public final int index = COUNT++; + + /** The index. */ + public final int index = COUNTER.GET(); + + /** The error. */ public String error; + /** + * Instantiates a new abstract summary. + * + * @param statement + * the statement + */ public AbstractSummary(final S statement) { if (statement != null) { title = statement.getTitleForSummary(); @@ -35,79 +55,147 @@ public AbstractSummary(final S statement) { } } - public void setError(final String error) { - this.error = error; - } - - public String getError() { - return error; - } - - public int getIndex() { - return index; - } - - public URI getURI() { - return uri; - } - - public String getTitle() { - return title; - } - + /** + * Sets the error. + * + * @param error + * the new error + */ + public void setError(final String error) { this.error = error; } + + /** + * Gets the error. + * + * @return the error + */ + public String getError() { return error; } + + /** + * Gets the index. + * + * @return the index + */ + public int getIndex() { return index; } + + /** + * Gets the uri. + * + * @return the uri + */ + public URI getURI() { return uri; } + + /** + * Gets the title. + * + * @return the title + */ + public String getTitle() { return title; } + + /** + * Gets the time stamp. + * + * @return the time stamp + */ public abstract long getTimeStamp(); - public GamaColor getColor() { - return getState().getColor(); - } - + /** + * Gets the color. + * + * @return the color + */ + public GamaColor getColor() { return getState().getColor(); } + + /** + * Gets the state. + * + * @return the state + */ public abstract TestState getState(); + /** + * Sets the state. + * + * @param state + * the new state + */ public abstract void setState(TestState state); + /** + * Reset. + */ public void reset() { error = null; } + /** + * Gets the summaries. + * + * @return the summaries + */ public abstract Map> getSummaries(); + /** + * Count tests with. + * + * @param state + * the state + * @return the int + */ public abstract int countTestsWith(final TestState state); + /** + * Size. + * + * @return the int + */ public abstract int size(); @Override public final String toString() { final TestState state = getState(); - if (GamaPreferences.Runtime.FAILED_TESTS.getValue() && state != TestState.FAILED - && state != TestState.ABORTED) { + if (GamaPreferences.Runtime.FAILED_TESTS.getValue() && state != TestState.FAILED && state != TestState.ABORTED) return ""; - } final StringBuilder sb = new StringBuilder(); printHeader(sb); sb.append(state).append(": ").append(getTitle()).append(" "); - if (error != null) { - sb.append('[').append(error).append(']'); - } + if (error != null) { sb.append('[').append(error).append(']'); } printFooter(sb); for (final AbstractSummary summary : getSummaries().values()) { final String child = summary.toString(); - if (child.isEmpty()) { - continue; - } + if (child.isEmpty()) { continue; } sb.append(child); } return sb.toString(); } + /** + * Prints the footer. + * + * @param sb + * the sb + */ protected void printFooter(final StringBuilder sb) {} + /** + * Prints the header. + * + * @param sb + * the sb + */ protected void printHeader(final StringBuilder sb) {} + /** + * Gets the summary of. + * + * @param uri + * the uri + * @return the summary of + */ public AbstractSummary getSummaryOf(final URI uri) { // if (this.uri != null) { // DEBUG.OUT("Comparing " + this.uri + " to " + uri); // } - if (uri.equals(this.uri)) { return this; } + if (uri.equals(this.uri)) return this; return StreamEx.ofValues(getSummaries()).findFirst(s -> s.getSummaryOf(uri) != null).orElse(null); } diff --git a/msi.gama.core/src/msi/gaml/types/GamaColorType.java b/msi.gama.core/src/msi/gaml/types/GamaColorType.java index cc34ba003f..6d1212caa3 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaColorType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaColorType.java @@ -41,6 +41,7 @@ public class GamaColorType extends GamaType { @Override + @doc("Transforms the parameter into a rgb color. A second parameter can be used to express the transparency of the color, either an int (between 0 and 255) or a float (between 0 and 1)") public GamaColor cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { return staticCast(scope, obj, param, copy); @@ -63,7 +64,7 @@ public static GamaColor staticCast(final IScope scope, final Object obj, final O if (obj instanceof List) { final List l = (List) obj; final int size = l.size(); - if (size == 0) { return new GamaColor(Color.black); } + if (size == 0) { return new GamaColor(Color.black); } if (size == 1 || size == 2) { return staticCast(scope, ((List) obj).get(0), param, copy); } else if (size == 3) { diff --git a/msi.gama.core/src/msi/gaml/types/GamaFileType.java b/msi.gama.core/src/msi/gaml/types/GamaFileType.java index 1f83fa5ae0..6ea5272cf0 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaFileType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaFileType.java @@ -51,13 +51,13 @@ public class GamaFileType extends GamaContainerType { /** The extensions to full type. */ - public static Map extensionsToFullType = GamaMapFactory.createUnordered(); + public static final Map extensionsToFullType = GamaMapFactory.createUnordered(); /** The aliases to full type. */ - static Map aliasesToFullType = GamaMapFactory.createUnordered(); + static final Map aliasesToFullType = GamaMapFactory.createUnordered(); /** The aliases to extensions. */ - static Multimap aliasesToExtensions = HashMultimap. create(); + static final Multimap aliasesToExtensions = HashMultimap. create(); /** The current file type index. */ static int currentFileTypeIndex = 1000; diff --git a/msi.gama.core/src/msi/gaml/types/GamaFontType.java b/msi.gama.core/src/msi/gaml/types/GamaFontType.java index 1c17796d20..5d8184e265 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaFontType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaFontType.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaFontType.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaFontType.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -41,28 +41,35 @@ concept = { IConcept.TYPE, IConcept.TEXT, IConcept.DISPLAY }) public class GamaFontType extends GamaType { - public static Pref DEFAULT_DISPLAY_FONT = GamaPreferences + /** The Constant DEFAULT_DISPLAY_FONT. */ + public static final Pref DEFAULT_DISPLAY_FONT = GamaPreferences .create("pref_display_default_font", "Default font to use in 'draw'", () -> new GamaFont("Helvetica", Font.PLAIN, 12), IType.FONT, true) .in(GamaPreferences.Displays.NAME, GamaPreferences.Displays.DRAWING); - @doc(value="Cast any object as a font", - usages = { - @usage(value = "if the operand is a number, returns with the operand value as font size and the default display font style", - examples = { - @example("font f <- font(12);") - }), - @usage(value = "if the operand is a string, returns a font with this font name", - examples = { - @example("font f <- font(12);") - }), - }) + @doc ( + value = "Cast any object as a font", + usages = { @usage ( + value = "if the operand is a number, returns with the operand value as font size and the default display font style", + examples = { @example ("font f <- font(12);") }), + @usage ( + value = "if the operand is a string, returns a font with this font name", + examples = { @example ("font f <- font(12);") }), }) @Override public GamaFont cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { return staticCast(scope, obj, copy); } + /** + * Static cast. + * + * @param scope the scope + * @param obj the obj + * @param copy the copy + * @return the gama font + * @throws GamaRuntimeException the gama runtime exception + */ public static GamaFont staticCast(final IScope scope, final Object obj, final boolean copy) throws GamaRuntimeException { if (obj instanceof Number) { @@ -71,20 +78,15 @@ public static GamaFont staticCast(final IScope scope, final Object obj, final bo return new GamaFont(font.getName(), font.getStyle(), size.intValue()); } if (obj instanceof GamaFont) { - if (copy) { - return new GamaFont((Font) obj); - } else { - return (GamaFont) obj; - } + if (copy) return new GamaFont((Font) obj); + return (GamaFont) obj; } - if (obj instanceof String) { return new GamaFont(Font.decode((String) obj)); } + if (obj instanceof String) return new GamaFont(Font.decode((String) obj)); return DEFAULT_DISPLAY_FONT.getValue(); } @Override - public GamaFont getDefault() { - return DEFAULT_DISPLAY_FONT.getValue(); - } + public GamaFont getDefault() { return DEFAULT_DISPLAY_FONT.getValue(); } @Override public boolean canCastToConst() { diff --git a/msi.gama.core/src/msi/gaml/types/GamaGeometryType.java b/msi.gama.core/src/msi/gaml/types/GamaGeometryType.java index f00891ad59..181b6efa0d 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaGeometryType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaGeometryType.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaGeometryType.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * GamaGeometryType.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.types; @@ -84,7 +84,8 @@ @SuppressWarnings ({ "unchecked", "rawtypes" }) public class GamaGeometryType extends GamaType { - public static WKTReader SHAPE_READER = new WKTReader(); + /** The Constant SHAPE_READER. */ + public static final WKTReader SHAPE_READER = new WKTReader(); @Override public IShape cast(final IScope scope, final Object obj, final Object param, final boolean copy) @@ -92,6 +93,16 @@ public IShape cast(final IScope scope, final Object obj, final Object param, fin return staticCast(scope, obj, param, copy); } + /** + * Static cast. + * + * @param scope the scope + * @param obj the obj + * @param param the param + * @param copy the copy + * @return the i shape + * @throws GamaRuntimeException the gama runtime exception + */ public static IShape staticCast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { @@ -128,26 +139,18 @@ public static IShape staticCast(final IScope scope, final Object obj, final Obje * @return */ private static boolean isPoints(final IScope scope, final IContainer obj) { - for (final Object o : obj.iterable(scope)) { - if (!(o instanceof GamaPoint)) return false; - } + for (final Object o : obj.iterable(scope)) { if (!(o instanceof GamaPoint)) return false; } return true; } @Override - public GamaShape getDefault() { - return null; - } + public GamaShape getDefault() { return null; } @Override - public boolean isDrawable() { - return true; - } + public boolean isDrawable() { return true; } @Override - public IType getKeyType() { - return Types.STRING; - } + public IType getKeyType() { return Types.STRING; } // // @Override @@ -156,9 +159,7 @@ public IType getKeyType() { // } @Override - public boolean isFixedLength() { - return false; - } + public boolean isFixedLength() { return false; } @Override public boolean canCastToConst() { @@ -202,6 +203,12 @@ public static IShape buildPolygon(final List points) { // GeometryUtils.changeClockWise(p)); } + /** + * Builds the multi polygon. + * + * @param lpoints the lpoints + * @return the i shape + */ // A.G 28/05/2015 ADDED for gamanalyser public static IShape buildMultiPolygon(final List> lpoints) { final Polygon[] polys = new Polygon[lpoints.size()]; @@ -231,6 +238,14 @@ public static IShape buildMultiPolygon(final List> lpoints) { return new GamaShape(m.buffer(0.0)); } + /** + * Builds the triangle. + * + * @param base the base + * @param height the height + * @param location the location + * @return the i shape + */ public static IShape buildTriangle(final double base, final double height, final GamaPoint location) { final Coordinate[] points = new Coordinate[4]; final double z = location == null ? 0.0 : location.getZ(); @@ -247,6 +262,13 @@ public static IShape buildTriangle(final double base, final double height, final return s; } + /** + * Builds the triangle. + * + * @param side_size the side size + * @param location the location + * @return the i shape + */ public static IShape buildTriangle(final double side_size, final GamaPoint location) { final double h = Math.sqrt(3) / 2 * side_size; final Coordinate[] points = new Coordinate[4]; @@ -264,6 +286,14 @@ public static IShape buildTriangle(final double side_size, final GamaPoint locat return new GamaShape(p); } + /** + * Builds the rectangle. + * + * @param width the width + * @param height the height + * @param location the location + * @return the i shape + */ public static IShape buildRectangle(final double width, final double height, final GamaPoint location) { final Coordinate[] points = new Coordinate[5]; final double x = location == null ? 0 : location.getX(); @@ -296,10 +326,23 @@ public static IShape buildPolyhedron(final List points, final Double dep return g; } + /** + * Builds the line. + * + * @param location2 the location 2 + * @return the i shape + */ public static IShape buildLine(final IShape location2) { return buildLine(new GamaPoint(), location2); } + /** + * Builds the line. + * + * @param location1 the location 1 + * @param location2 the location 2 + * @return the i shape + */ public static IShape buildLine(final IShape location1, final IShape location2) { final Coordinate coordinates[] = { location1 == null ? new GamaPoint(0, 0) : (GamaPoint) location1.getLocation(), @@ -311,6 +354,14 @@ public static IShape buildLine(final IShape location1, final IShape location2) { return new GamaShape(GeometryUtils.GEOMETRY_FACTORY.createLineString(coordinates)); } + /** + * Builds the line cylinder. + * + * @param location1 the location 1 + * @param location2 the location 2 + * @param radius the radius + * @return the i shape + */ public static IShape buildLineCylinder(final IShape location1, final IShape location2, final double radius) { final IShape g = buildLine(location1, location2); g.setDepth(radius); @@ -318,6 +369,14 @@ public static IShape buildLineCylinder(final IShape location1, final IShape loca return g; } + /** + * Builds the plan. + * + * @param location1 the location 1 + * @param location2 the location 2 + * @param depth the depth + * @return the i shape + */ public static IShape buildPlan(final IShape location1, final IShape location2, final Double depth) { final IShape g = buildLine(location1, location2); g.setDepth(depth); @@ -325,15 +384,26 @@ public static IShape buildPlan(final IShape location1, final IShape location2, f return g; } + /** + * Builds the polyline. + * + * @param points the points + * @return the i shape + */ public static IShape buildPolyline(final List points) { final List coordinates = new ArrayList<>(); - for (final IShape p : points) { - coordinates.add(p.getLocation()); - } + for (final IShape p : points) { coordinates.add(p.getLocation()); } return new GamaShape(GeometryUtils.GEOMETRY_FACTORY .createLineString(coordinates.toArray(new Coordinate[coordinates.size()]))); } + /** + * Builds the polyline cylinder. + * + * @param points the points + * @param radius the radius + * @return the i shape + */ public static IShape buildPolylineCylinder(final List points, final double radius) { final IShape g = buildPolyline(points); g.setDepth(radius); @@ -341,6 +411,13 @@ public static IShape buildPolylineCylinder(final List points, final doub return g; } + /** + * Builds the polyplan. + * + * @param points the points + * @param depth the depth + * @return the i shape + */ public static IShape buildPolyplan(final List points, final Double depth) { final IShape g = buildPolyline(points); g.setDepth(depth); @@ -348,15 +425,35 @@ public static IShape buildPolyplan(final List points, final Double depth return g; } + /** + * Creates the point. + * + * @param location the location + * @return the gama shape + */ public static GamaShape createPoint(final IShape location) { return new GamaShape(GeometryUtils.GEOMETRY_FACTORY .createPoint(location == null ? new GamaPoint(0, 0) : (GamaPoint) location.getLocation())); } + /** + * Builds the square. + * + * @param side_size the side size + * @param location the location + * @return the i shape + */ public static IShape buildSquare(final double side_size, final GamaPoint location) { return buildRectangle(side_size, side_size, location); } + /** + * Builds the cube. + * + * @param side_size the side size + * @param location the location + * @return the i shape + */ public static IShape buildCube(final double side_size, final GamaPoint location) { final IShape g = buildRectangle(side_size, side_size, location); @@ -366,6 +463,15 @@ public static IShape buildCube(final double side_size, final GamaPoint location) } + /** + * Builds the box. + * + * @param width the width + * @param height the height + * @param depth the depth + * @param location the location + * @return the i shape + */ public static IShape buildBox(final double width, final double height, final double depth, final GamaPoint location) { final IShape g = buildRectangle(width, height, location); @@ -374,14 +480,37 @@ public static IShape buildBox(final double width, final double height, final dou return g; } + /** + * Builds the hexagon. + * + * @param size the size + * @param x the x + * @param y the y + * @return the i shape + */ public static IShape buildHexagon(final double size, final double x, final double y) { return buildHexagon(size, new GamaPoint(x, y)); } + /** + * Builds the hexagon. + * + * @param size the size + * @param location the location + * @return the i shape + */ public static IShape buildHexagon(final double size, final GamaPoint location) { return buildHexagon(size, size, location); } + /** + * Builds the hexagon. + * + * @param sizeX the size X + * @param sizeY the size Y + * @param location the location + * @return the i shape + */ public static IShape buildHexagon(final double sizeX, final double sizeY, final GamaPoint location) { final double x = location.getX(); final double y = location.getY(); @@ -399,21 +528,34 @@ public static IShape buildHexagon(final double sizeX, final double sizeY, final } + /** + * Builds the circle. + * + * @param radius the radius + * @param location the location + * @return the i shape + */ public static IShape buildCircle(final double radius, final GamaPoint location) { final Geometry geom = GeometryUtils.GEOMETRY_FACTORY .createPoint(location == null ? new GamaPoint(0, 0) : (GamaPoint) location); final Geometry g = geom.buffer(radius); if (location != null) { final Coordinate[] coordinates = g.getCoordinates(); - for (int i = 0; i < coordinates.length; i++) { - coordinates[i].z = location.z; - } + for (int i = 0; i < coordinates.length; i++) { coordinates[i].z = location.z; } } return new GamaShape(g); } + /** + * Builds the ellipse. + * + * @param xRadius the x radius + * @param yRadius the y radius + * @param location the location + * @return the i shape + */ public static IShape buildEllipse(final double xRadius, final double yRadius, final GamaPoint location) { - if ((xRadius <= 0) && (yRadius <= 0)) return new GamaShape(location); + if (xRadius <= 0 && yRadius <= 0) return new GamaShape(location); final GeometricShapeFactory factory = new GeometricShapeFactory(GeometryUtils.GEOMETRY_FACTORY); factory.setNumPoints(GamaPreferences.Displays.DISPLAY_SLICE_NUMBER.getValue()); // WARNING AD Arbitrary number. // Maybe add a @@ -424,13 +566,19 @@ public static IShape buildEllipse(final double xRadius, final double yRadius, fi final Geometry g = factory.createEllipse(); if (location != null) { final Coordinate[] coordinates = g.getCoordinates(); - for (int i = 0; i < coordinates.length; i++) { - coordinates[i].z = location.z; - } + for (int i = 0; i < coordinates.length; i++) { coordinates[i].z = location.z; } } return new GamaShape(g); } + /** + * Builds the squircle. + * + * @param xRadius the x radius + * @param power the power + * @param location the location + * @return the i shape + */ public static IShape buildSquircle(final double xRadius, final double power, final GamaPoint location) { if (xRadius <= 0) return new GamaShape(location); final GeometricShapeFactory factory = new GeometricShapeFactory(GeometryUtils.GEOMETRY_FACTORY); @@ -442,9 +590,7 @@ public static IShape buildSquircle(final double xRadius, final double power, fin final Geometry g = factory.createSupercircle(power); if (location != null) { final Coordinate[] coordinates = g.getCoordinates(); - for (int i = 0; i < coordinates.length; i++) { - coordinates[i].z = location.z; - } + for (int i = 0; i < coordinates.length; i++) { coordinates[i].z = location.z; } } return new GamaShape(g); @@ -482,14 +628,20 @@ public static IShape buildArc(final double xRadius, final double heading, final } if (location != null) { final Coordinate[] coordinates = g.getCoordinates(); - for (int i = 0; i < coordinates.length; i++) { - coordinates[i].z = location.z; - } + for (int i = 0; i < coordinates.length; i++) { coordinates[i].z = location.z; } } return new GamaShape(g); } + /** + * Builds the cylinder. + * + * @param radius the radius + * @param depth the depth + * @param location the location + * @return the i shape + */ public static IShape buildCylinder(final double radius, final double depth, final GamaPoint location) { final IShape g = buildCircle(radius, location); g.setDepth(depth); @@ -497,6 +649,13 @@ public static IShape buildCylinder(final double radius, final double depth, fina return g; } + /** + * Builds the sphere. + * + * @param radius the radius + * @param location the location + * @return the i shape + */ // FIXME: Be sure that a buffer on a sphere returns a sphere. public static IShape buildSphere(final double radius, final GamaPoint location) { final IShape g = buildCircle(radius, location); @@ -505,6 +664,14 @@ public static IShape buildSphere(final double radius, final GamaPoint location) return g; } + /** + * Builds the cone 3 D. + * + * @param radius the radius + * @param depth the depth + * @param location the location + * @return the i shape + */ public static IShape buildCone3D(final double radius, final double depth, final GamaPoint location) { final IShape g = buildCircle(radius, location); g.setDepth(depth); @@ -512,6 +679,13 @@ public static IShape buildCone3D(final double radius, final double depth, final return g; } + /** + * Builds the teapot. + * + * @param size the size + * @param location the location + * @return the i shape + */ public static IShape buildTeapot(final double size, final GamaPoint location) { final IShape g = buildCircle(size, location); g.setDepth(size); @@ -519,6 +693,13 @@ public static IShape buildTeapot(final double size, final GamaPoint location) { return g; } + /** + * Builds the pyramid. + * + * @param side_size the side size + * @param location the location + * @return the i shape + */ public static IShape buildPyramid(final double side_size, final GamaPoint location) { final IShape g = buildRectangle(side_size, side_size, location); g.setDepth(side_size); @@ -526,12 +707,30 @@ public static IShape buildPyramid(final double side_size, final GamaPoint locati return g; } + /** The theta. */ private static double theta = Math.tan(0.423d); + /** + * Builds the arrow. + * + * @param head the head + * @param size the size + * @return the i shape + */ public static IShape buildArrow(final GamaPoint head, final double size) { return buildArrow(new GamaPoint(), head, size, size, true); } + /** + * Builds the arrow. + * + * @param tail the tail + * @param head the head + * @param arrowWidth the arrow width + * @param arrowLength the arrow length + * @param closed the closed + * @return the i shape + */ public static IShape buildArrow(final GamaPoint tail, final GamaPoint head, final double arrowWidth, final double arrowLength, final boolean closed) { final IList points = GamaListFactory.createWithoutCasting(Types.POINT, head); @@ -556,6 +755,14 @@ public static IShape buildArrow(final GamaPoint tail, final GamaPoint head, fina return closed ? buildPolygon(points) : buildPolyline(points); } + /** + * Geometries to geometry. + * + * @param scope the scope + * @param ags the ags + * @return the gama shape + * @throws GamaRuntimeException the gama runtime exception + */ public static GamaShape geometriesToGeometry(final IScope scope, final IContainer ags) throws GamaRuntimeException { if (ags == null || ags.isEmpty(scope)) return null; @@ -579,9 +786,7 @@ public static GamaShape geometriesToGeometry(final IScope scope, final IContaine if (geom != null && !geom.isEmpty()) return new GamaShape(geom); } else if (is_polyline) { final LineMerger merger = new LineMerger(); - for (final Geometry g : geoms) { - merger.add(g); - } + for (final Geometry g : geoms) { merger.add(g); } final Collection collection = merger.getMergedLineStrings(); Geometry geom = @@ -597,19 +802,24 @@ public static GamaShape geometriesToGeometry(final IScope scope, final IContaine } catch (final AssertionFailedException | TopologyException | IllegalArgumentException e) { // Geometry gs[] = new Geometry[geoms.length]; final List gs = new ArrayList(geoms.size()); - for (final Geometry g : geoms) { - gs.add(g.buffer(0.0)); - } + for (final Geometry g : geoms) { gs.add(g.buffer(0.0)); } try { final Geometry geom = CascadedPolygonUnion.union(gs); if (geom != null && !geom.isEmpty()) return new GamaShape(geom); - } catch (final AssertionFailedException | TopologyException | IllegalArgumentException e2) { - } + } catch (final AssertionFailedException | TopologyException | IllegalArgumentException e2) {} } return null; } + /** + * Points to geometry. + * + * @param scope the scope + * @param coordinates the coordinates + * @return the gama shape + * @throws GamaRuntimeException the gama runtime exception + */ public static GamaShape pointsToGeometry(final IScope scope, final IContainer coordinates) throws GamaRuntimeException { if (coordinates != null && !coordinates.isEmpty(scope)) { @@ -624,10 +834,26 @@ public static GamaShape pointsToGeometry(final IScope scope, final IContainer shapes) { if (shapes.size() == 0) return null; if (shapes.size() == 1) return shapes.get(0); @@ -644,15 +876,27 @@ public static IShape buildMultiGeometry(final IList shapes) { return new GamaShape(geom); } + /** + * Builds the multi geometry. + * + * @param shapes the shapes + * @return the i shape + */ public static IShape buildMultiGeometry(final IShape... shapes) { try (final Collector.AsList list = Collector.getList()) { - for (final IShape shape : shapes) { - if (shape != null) { list.add(shape); } - } + for (final IShape shape : shapes) { if (shape != null) { list.add(shape); } } return buildMultiGeometry(list.items()); } } + /** + * Builds the cross. + * + * @param xRadius the x radius + * @param width the width + * @param location the location + * @return the i shape + */ public static IShape buildCross(final Double xRadius, final Double width, final GamaPoint location) { if (xRadius <= 0) return new GamaShape(location); final double val = xRadius / Math.sqrt(2); diff --git a/msi.gama.core/src/msi/gaml/types/GamaIntegerType.java b/msi.gama.core/src/msi/gaml/types/GamaIntegerType.java index bb6f4e1b80..d9530bfdf0 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaIntegerType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaIntegerType.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaIntegerType.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaIntegerType.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.types; @@ -40,16 +40,32 @@ public class GamaIntegerType extends GamaType { @Override + @doc ("Returns the parameter casted to an int value. If it is an integer, returns it. A float, returns its integer value. " + + "A color, its rgb value. An agent, its index. A string, attempts to parse it (with a radix of 16 if it begins with '#'). " + + "A bool, return 1 if true. A font, return its size. Otherwise return 0") public Integer cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { return staticCast(scope, obj, param, copy); } + /** + * Static cast. + * + * @param scope + * the scope + * @param obj + * the obj + * @param param + * the param + * @param copy + * the copy + * @return the integer + */ public static Integer staticCast(final IScope scope, final Object obj, final Object param, final boolean copy) { - if (obj instanceof Integer) { return (Integer) obj; } - if (obj instanceof Number) { return ((Number) obj).intValue(); } - if (obj instanceof Color) { return ((Color) obj).getRGB(); } - if (obj instanceof IAgent) { return ((IAgent) obj).getIndex(); } + if (obj instanceof Integer) return (Integer) obj; + if (obj instanceof Number) return ((Number) obj).intValue(); + if (obj instanceof Color) return ((Color) obj).getRGB(); + if (obj instanceof IAgent) return ((IAgent) obj).getIndex(); if (obj instanceof String) { String n = obj.toString(); // removing whitespaces @@ -57,15 +73,13 @@ public static Integer staticCast(final IScope scope, final Object obj, final Obj try { // If the string contains an hexadecimal number, parse it with a // radix of 16. - if (n.startsWith("#")) { return Integer.parseInt(n.substring(1), 16); } + if (n.startsWith("#")) return Integer.parseInt(n.substring(1), 16); // Otherwise use by default a "natural" radix of 10 (can be // bypassed with the // as_int operator, which will put the radix in the param // argument) int radix = 10; - if (param instanceof Integer) { - radix = (Integer) param; - } + if (param instanceof Integer) { radix = (Integer) param; } return Integer.parseInt(n, radix); } catch (final NumberFormatException e) { // for ( Character c : n.toCharArray() ) { @@ -83,17 +97,14 @@ public static Integer staticCast(final IScope scope, final Object obj, final Obj return d.intValue(); } } - if (obj instanceof Boolean) { return (Boolean) obj ? 1 : 0; } - if (obj instanceof GamaFont) { return ((GamaFont) obj).getSize(); } - if (obj instanceof GamaDate) - return ((GamaDate) obj).intValue(scope); + if (obj instanceof Boolean) return (Boolean) obj ? 1 : 0; + if (obj instanceof GamaFont) return ((GamaFont) obj).getSize(); + if (obj instanceof GamaDate) return ((GamaDate) obj).intValue(scope); return 0; } @Override - public Integer getDefault() { - return 0; - } + public Integer getDefault() { return 0; } @Override public boolean isTranslatableInto(final IType type) { @@ -102,7 +113,7 @@ public boolean isTranslatableInto(final IType type) { @Override public IType coerce(final IType type, final IDescription context) { - if (type == this) { return null; } + if (type == this) return null; return this; } @@ -121,8 +132,6 @@ public boolean canCastToConst() { } @Override - public boolean isNumber() { - return true; - } + public boolean isNumber() { return true; } } diff --git a/msi.gama.core/src/msi/gaml/types/GamaNoType.java b/msi.gama.core/src/msi/gaml/types/GamaNoType.java index 112035a151..2595e3931c 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaNoType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaNoType.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaNoType.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaNoType.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -36,15 +36,14 @@ public class GamaNoType extends GamaType { @Override + @doc ("Returns the parameter itself") public Object cast(final IScope scope, final Object obj, final Object param, final boolean copy) { // WARNING: Should we obey the "copy" parameter in this case ? return obj; } @Override - public Object getDefault() { - return null; - } + public Object getDefault() { return null; } @Override public boolean isSuperTypeOf(final IType type) { diff --git a/msi.gama.core/src/msi/gaml/types/GamaPointType.java b/msi.gama.core/src/msi/gaml/types/GamaPointType.java index caf3bd443f..beecb5ba35 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaPointType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaPointType.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaPointType.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * GamaPointType.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -43,11 +43,25 @@ public class GamaPointType extends GamaType { @Override + @doc ("Transforms the parameter into a point. If it is already a point, returns it. " + + "If it is a geometry, returns its location. If it is a list, interprets its elements as float values and use up to the first 3 ones to return a point. " + + "If it is a map, tries to find 'x', 'y' and 'z' keys in it. If it is a number, returns a point with the x, y and equal to this value") public GamaPoint cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { return staticCast(scope, obj, copy); } + /** + * Static cast. + * + * @param scope + * the scope + * @param obj + * the obj + * @param copy + * the copy + * @return the gama point + */ public static GamaPoint staticCast(final IScope scope, final Object obj, final boolean copy) { if (obj instanceof GamaPoint) return (GamaPoint) obj; if (obj instanceof IShape) return ((IShape) obj).getLocation(); @@ -82,19 +96,13 @@ public static GamaPoint staticCast(final IScope scope, final Object obj, final b } @Override - public GamaPoint getDefault() { - return null; - } + public GamaPoint getDefault() { return null; } @Override - public IType getContentType() { - return Types.get(FLOAT); - } + public IType getContentType() { return Types.get(FLOAT); } @Override - public IType getKeyType() { - return Types.get(INT); - } + public IType getKeyType() { return Types.get(INT); } @Override public boolean canCastToConst() { @@ -102,13 +110,9 @@ public boolean canCastToConst() { } @Override - public boolean isDrawable() { - return true; - } + public boolean isDrawable() { return true; } @Override - public boolean isCompoundType() { - return true; - } + public boolean isCompoundType() { return true; } } diff --git a/msi.gama.core/src/msi/gaml/types/GamaSkillType.java b/msi.gama.core/src/msi/gaml/types/GamaSkillType.java index a16385c859..bacf035616 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaSkillType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaSkillType.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaSkillType.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaSkillType.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -39,17 +39,16 @@ public class GamaSkillType extends GamaType { @Override + @doc ("Tries to convert the parameter to a skill. If it is a skill already, returns it. If it is a string, returns it if it is registered in GAMA. Otherwise return null") public ISkill cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { - if (obj instanceof ISkill) { return (ISkill) obj; } - if (obj instanceof String) { return GamaSkillRegistry.INSTANCE.getSkillInstanceFor((String) obj); } + if (obj instanceof ISkill) return (ISkill) obj; + if (obj instanceof String) return GamaSkillRegistry.INSTANCE.getSkillInstanceFor((String) obj); return null; } @Override - public ISkill getDefault() { - return null; - } + public ISkill getDefault() { return null; } @Override public boolean canCastToConst() { diff --git a/msi.gama.core/src/msi/gaml/types/GamaSpeciesType.java b/msi.gama.core/src/msi/gaml/types/GamaSpeciesType.java index ad9e2db268..eb7f6604c6 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaSpeciesType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaSpeciesType.java @@ -1,12 +1,12 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaSpeciesType.java, in plugin msi.gama.core, is part of the source code of the GAMA modeling and - * simulation platform (v. 1.8.1) + * GamaSpeciesType.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.types; @@ -41,16 +41,15 @@ public class GamaSpeciesType extends GamaContainerType { @Override + @doc ("Transforms the parameter into a species. If it is already a species, returns it. If it is an agent, returns its species. If it is a string, returns the species named this way. Otherwise returns null.") public ISpecies cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { // TODO Add a more general cast with list of agents to find a common // species. - ISpecies species = obj == null ? getDefault() - : obj instanceof ISpecies ? (ISpecies) obj : obj instanceof IAgent ? ((IAgent) obj).getSpecies() - : obj instanceof String ? scope.getModel().getSpecies((String) obj) : getDefault(); - if (obj instanceof IPopulationSet) { - species = ((IPopulationSet) obj).getSpecies(); - } + ISpecies species = obj == null ? getDefault() : obj instanceof ISpecies ? (ISpecies) obj + : obj instanceof IAgent ? ((IAgent) obj).getSpecies() + : obj instanceof String ? scope.getModel().getSpecies((String) obj) : getDefault(); + if (obj instanceof IPopulationSet) { species = ((IPopulationSet) obj).getSpecies(); } return species; } @@ -59,38 +58,28 @@ public ISpecies cast(final IScope scope, final Object obj, final Object param, f final IType contentType, final boolean copy) { final ISpecies result = cast(scope, obj, param, copy); - if (result == null) { - if (contentType.isAgentType()) { return scope.getModel().getSpecies(contentType.getName()); } - } + if ((result == null) && contentType.isAgentType()) return scope.getModel().getSpecies(contentType.getName()); return result; } // TODO Verify that we dont need to declare the other cast method @Override - public ISpecies getDefault() { - return null; - } + public ISpecies getDefault() { return null; } @Override - public IType getContentType() { - return Types.get(AGENT); - } + public IType getContentType() { return Types.get(AGENT); } @Override - public IType getKeyType() { - return Types.INT; - } + public IType getKeyType() { return Types.INT; } @Override - public boolean isDrawable() { - return true; - } + public boolean isDrawable() { return true; } @Override public IType contentsTypeIfCasting(final IExpression exp) { final IType itemType = exp.getGamlType(); - if (itemType.isAgentType()) { return itemType; } + if (itemType.isAgentType()) return itemType; switch (exp.getGamlType().id()) { case SPECIES: return itemType.getContentType(); diff --git a/msi.gama.core/src/msi/gaml/types/GamaStringType.java b/msi.gama.core/src/msi/gaml/types/GamaStringType.java index 78902b21a7..1e687cd475 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaStringType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaStringType.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaStringType.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaStringType.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -27,7 +27,7 @@ * Written by drogoul Modified on 3 juin 2010 * * @todo Description - * + * */ @SuppressWarnings ("unchecked") @type ( @@ -40,23 +40,31 @@ public class GamaStringType extends GamaType { @Override + @doc ("Transforms the parameter into a string") public String cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { return staticCast(scope, obj, copy); } + /** + * Static cast. + * + * @param scope the scope + * @param obj the obj + * @param copy the copy + * @return the string + * @throws GamaRuntimeException the gama runtime exception + */ public static String staticCast(final IScope scope, final Object obj, final boolean copy) throws GamaRuntimeException { - if (obj == null) { return null; } - if (obj instanceof IValue) { return ((IValue) obj).stringValue(scope); } - if (obj instanceof INamed) { return ((INamed) obj).getName(); } + if (obj == null) return null; + if (obj instanceof IValue) return ((IValue) obj).stringValue(scope); + if (obj instanceof INamed) return ((INamed) obj).getName(); return obj.toString(); } @Override - public String getDefault() { - return null; - } + public String getDefault() { return null; } @Override public boolean canCastToConst() { @@ -64,8 +72,6 @@ public boolean canCastToConst() { } @Override - public boolean isDrawable() { - return true; - } + public boolean isDrawable() { return true; } } diff --git a/msi.gama.core/src/msi/gaml/types/GamaTopologyType.java b/msi.gama.core/src/msi/gaml/types/GamaTopologyType.java index 2cf0a8b339..213857c1f9 100644 --- a/msi.gama.core/src/msi/gaml/types/GamaTopologyType.java +++ b/msi.gama.core/src/msi/gaml/types/GamaTopologyType.java @@ -1,9 +1,9 @@ /******************************************************************************************************* * - * msi.gaml.types.GamaTopologyType.java, in plugin msi.gama.core, - * is part of the source code of the GAMA modeling and simulation platform (v. 1.8.1) + * GamaTopologyType.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2020 UMI 209 UMMISCO IRD/SU & Partners + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. * @@ -33,10 +33,10 @@ /** * The type topology. - * + * * @author Alexis Drogoul * @since 26 nov. 2011 - * + * */ @SuppressWarnings ("unchecked") @type ( @@ -48,20 +48,27 @@ doc = @doc ("Represents a topology, obtained from agents or geometries, that can be used to compute distances, neighbours, etc.")) public class GamaTopologyType extends GamaType { + /** + * Static cast. + * + * @param scope the scope + * @param obj the obj + * @param copy the copy + * @return the i topology + * @throws GamaRuntimeException the gama runtime exception + */ @SuppressWarnings ("rawtypes") public static ITopology staticCast(final IScope scope, final Object obj, final boolean copy) throws GamaRuntimeException { // Many cases. - if (obj == null) { return null; } - if (obj instanceof ISpatialGraph) { return ((ISpatialGraph) obj).getTopology(scope); } - if (obj instanceof ITopology) { return (ITopology) obj; } - if (obj instanceof IAgent) - return ((IAgent) obj).getTopology(); - if (obj instanceof IPopulation) { return ((IPopulation) obj).getTopology(); } - if (obj instanceof ISpecies) { return staticCast(scope, scope.getAgent().getPopulationFor((ISpecies) obj), - copy); } - if (obj instanceof IShape) { return from(scope, (IShape) obj); } - if (obj instanceof IContainer) { return from(scope, (IContainer) obj); } + if (obj == null) return null; + if (obj instanceof ISpatialGraph) return ((ISpatialGraph) obj).getTopology(scope); + if (obj instanceof ITopology) return (ITopology) obj; + if (obj instanceof IAgent) return ((IAgent) obj).getTopology(); + if (obj instanceof IPopulation) return ((IPopulation) obj).getTopology(); + if (obj instanceof ISpecies) return staticCast(scope, scope.getAgent().getPopulationFor((ISpecies) obj), copy); + if (obj instanceof IShape) return from(scope, (IShape) obj); + if (obj instanceof IContainer) return from(scope, (IContainer) obj); return staticCast(scope, Cast.asGeometry(scope, obj, copy), copy); } @@ -69,11 +76,19 @@ public static ITopology staticCast(final IScope scope, final Object obj, final b * @see msi.gama.internal.types.GamaType#cast(msi.gama.interfaces.IScope, java.lang.Object, java.lang.Object) */ @Override + @doc ("Transforms the parameter into a usable topology") public ITopology cast(final IScope scope, final Object obj, final Object param, final boolean copy) throws GamaRuntimeException { return staticCast(scope, obj, copy); } + /** + * From. + * + * @param scope the scope + * @param obj the obj + * @return the i topology + */ public static ITopology from(final IScope scope, final IShape obj) { return new ContinuousTopology(scope, obj); } @@ -85,27 +100,21 @@ public static ITopology from(final IScope scope, final IShape obj) { * @return */ private static ITopology from(final IScope scope, final IContainer obj) throws GamaRuntimeException { - if (obj instanceof GamaSpatialGraph) { - return ((GamaSpatialGraph) obj).getTopology(scope); - } else if (obj instanceof IGrid) { + if (obj instanceof GamaSpatialGraph) return ((GamaSpatialGraph) obj).getTopology(scope); + if (obj instanceof IGrid) return new GridTopology(scope, (IGrid) obj); - } else { + else return new MultipleTopology(scope, obj); - } } /** * @see msi.gama.internal.types.GamaType#getDefault() */ @Override - public ITopology getDefault() { - return null; - } + public ITopology getDefault() { return null; } @Override - public IType getContentType() { - return Types.GEOMETRY; - } + public IType getContentType() { return Types.GEOMETRY; } @Override public boolean canCastToConst() { diff --git a/msi.gama.core/src/msi/gaml/types/ParametricFileType.java b/msi.gama.core/src/msi/gaml/types/ParametricFileType.java index cbcecb9b29..652fd04bae 100644 --- a/msi.gama.core/src/msi/gaml/types/ParametricFileType.java +++ b/msi.gama.core/src/msi/gaml/types/ParametricFileType.java @@ -48,7 +48,7 @@ public class ParametricFileType extends ParametricType { String plugin; /** The generic instance. */ - static ParametricFileType genericInstance; + static volatile ParametricFileType genericInstance; /** * Instantiates a new parametric file type. diff --git a/msi.gama.core/src/msi/gaml/types/Types.java b/msi.gama.core/src/msi/gaml/types/Types.java index 03729c63d7..76a8cc0465 100644 --- a/msi.gama.core/src/msi/gaml/types/Types.java +++ b/msi.gama.core/src/msi/gaml/types/Types.java @@ -349,7 +349,7 @@ public static void init() { } /** The built in species. */ - private static List builtInSpecies; + private static volatile List builtInSpecies; /** * Gets the built in species. diff --git a/msi.gama.core/src/msi/gaml/variables/Variable.java b/msi.gama.core/src/msi/gaml/variables/Variable.java index c05c672411..1d820a53a6 100644 --- a/msi.gama.core/src/msi/gaml/variables/Variable.java +++ b/msi.gama.core/src/msi/gaml/variables/Variable.java @@ -1,11 +1,12 @@ /******************************************************************************************************* * - * Variable.java, in msi.gama.core, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * Variable.java, in msi.gama.core, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). * - * (c) 2007-2021 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) * * Visit https://github.com/gama-platform/gama for license information and contacts. - * + * ********************************************************************************************************/ package msi.gaml.variables; @@ -160,7 +161,7 @@ public class Variable extends Symbol implements IVariable { public static class VarValidator implements IDescriptionValidator { /** The assignment facets. */ - public static List assignmentFacets = Arrays.asList(VALUE, INIT, FUNCTION, UPDATE, MIN, MAX); + public static final List assignmentFacets = Arrays.asList(VALUE, INIT, FUNCTION, UPDATE, MIN, MAX); /** * Method validate() diff --git a/msi.gama.documentation/src/msi/gama/doc/util/HomeToTOC.java b/msi.gama.documentation/src/msi/gama/doc/util/HomeToTOC.java index de36fb8b4c..dc4231a416 100644 --- a/msi.gama.documentation/src/msi/gama/doc/util/HomeToTOC.java +++ b/msi.gama.documentation/src/msi/gama/doc/util/HomeToTOC.java @@ -1,3 +1,13 @@ +/******************************************************************************************************* + * + * HomeToTOC.java, in msi.gama.documentation, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.doc.util; import java.io.BufferedReader; @@ -26,224 +36,308 @@ import msi.gama.precompiler.doc.utils.Constants; +/** + * The Class HomeToTOC. + */ public class HomeToTOC { - - public final static int MD_LEVEL_ERR = -1; // no header - public final static int MD_LEVEL0 = 0; // empty line - public final static int MD_LEVEL1 = 1; // # - public final static int MD_LEVEL2 = 2; // ## - public final static int MD_LEVEL3 = 3; // 1. - public final static int MD_LEVEL4 = 4; // 1. - - // XML Elements - public final static String XML_ELT_TOC = "toc"; - public final static String XML_ATTR_TITLE = "title"; - - public final static String XML_ELT_PART = "part"; - public final static String XML_ELT_SUBPART = "subpart"; - public final static String XML_ELT_CHAPTER = "chapter"; - - public final static String XML_ATTR_NAME = "name"; - public final static String XML_ATTR_FILE = "file"; - - // Toc file name - public final static String TITLE_MESSAGE = "Full Documentation of GAMA " + Constants.GAMA_VERSION; - public final static String DEFAULT_FILE = "G__BlankPage"; - - public final static String MD_EXTENSION = ".md"; - - - public static void md2toc(String tocMDFile, String savePath, String wikiFolder) { - String line = ""; + + /** The Constant MD_LEVEL_ERR. */ + public final static int MD_LEVEL_ERR = -1; // no header + + /** The Constant MD_LEVEL0. */ + public final static int MD_LEVEL0 = 0; // empty line + + /** The Constant MD_LEVEL1. */ + public final static int MD_LEVEL1 = 1; // # + + /** The Constant MD_LEVEL2. */ + public final static int MD_LEVEL2 = 2; // ## + + /** The Constant MD_LEVEL3. */ + public final static int MD_LEVEL3 = 3; // 1. + + /** The Constant MD_LEVEL4. */ + public final static int MD_LEVEL4 = 4; // 1. + + /** The Constant XML_ELT_TOC. */ + // XML Elements + public final static String XML_ELT_TOC = "toc"; + + /** The Constant XML_ATTR_TITLE. */ + public final static String XML_ATTR_TITLE = "title"; + + /** The Constant XML_ELT_PART. */ + public final static String XML_ELT_PART = "part"; + + /** The Constant XML_ELT_SUBPART. */ + public final static String XML_ELT_SUBPART = "subpart"; + + /** The Constant XML_ELT_CHAPTER. */ + public final static String XML_ELT_CHAPTER = "chapter"; + + /** The Constant XML_ATTR_NAME. */ + public final static String XML_ATTR_NAME = "name"; + + /** The Constant XML_ATTR_FILE. */ + public final static String XML_ATTR_FILE = "file"; + + /** The Constant TITLE_MESSAGE. */ + // Toc file name + public final static String TITLE_MESSAGE = "Full Documentation of GAMA " + Constants.GAMA_VERSION; + + /** The Constant DEFAULT_FILE. */ + public final static String DEFAULT_FILE = "G__BlankPage"; + + /** The Constant MD_EXTENSION. */ + public final static String MD_EXTENSION = ".md"; + + /** + * Md 2 toc. + * + * @param tocMDFile + * the toc MD file + * @param savePath + * the save path + * @param wikiFolder + * the wiki folder + */ + public static void md2toc(final String tocMDFile, final String savePath, final String wikiFolder) { + String line = ""; Document doc = createDocument(); - - // root element - Element root = doc.createElement(HomeToTOC.XML_ELT_TOC); - root.setAttribute(HomeToTOC.XML_ATTR_TITLE, HomeToTOC.TITLE_MESSAGE); - - Element currentPart = null; - Element currentSubPart = null; - + + // root element + Element root = doc.createElement(HomeToTOC.XML_ELT_TOC); + root.setAttribute(HomeToTOC.XML_ATTR_TITLE, HomeToTOC.TITLE_MESSAGE); + + Element currentPart = null; + Element currentSubPart = null; + try (BufferedReader br = new BufferedReader(new FileReader(tocMDFile));) { while ((line = br.readLine()) != null) { - switch (getLineHeader(line)) { - case HomeToTOC.MD_LEVEL2: - if(currentPart != null) { - if(currentSubPart != null) { - currentPart.appendChild(currentSubPart); - } - root.appendChild(currentPart); - } - // Create a new part - currentPart = doc.createElement(HomeToTOC.XML_ELT_PART); - currentPart.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); - // Create also a new subpart - currentSubPart = doc.createElement(HomeToTOC.XML_ELT_SUBPART); - currentSubPart.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); - currentSubPart.setAttribute(HomeToTOC.XML_ATTR_FILE, getLineFilePath(line,wikiFolder)); - break; - case HomeToTOC.MD_LEVEL3: - if( (currentPart != null) && (currentSubPart != null) ) { - currentPart.appendChild(currentSubPart); - } - currentSubPart = doc.createElement(HomeToTOC.XML_ELT_SUBPART); - currentSubPart.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); - currentSubPart.setAttribute(HomeToTOC.XML_ATTR_FILE, getLineFilePath(line,wikiFolder)); - break; - case HomeToTOC.MD_LEVEL4: - Element chapterElt = doc.createElement(HomeToTOC.XML_ELT_CHAPTER); - chapterElt.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); - chapterElt.setAttribute(HomeToTOC.XML_ATTR_FILE, getLineFilePath(line,wikiFolder)); - currentSubPart.appendChild(chapterElt); - break; - default: - break; - } + switch (getLineHeader(line)) { + case HomeToTOC.MD_LEVEL2: + if (currentPart != null) { + if (currentSubPart != null) { currentPart.appendChild(currentSubPart); } + root.appendChild(currentPart); + } + // Create a new part + currentPart = doc.createElement(HomeToTOC.XML_ELT_PART); + currentPart.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); + // Create also a new subpart + currentSubPart = doc.createElement(HomeToTOC.XML_ELT_SUBPART); + currentSubPart.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); + currentSubPart.setAttribute(HomeToTOC.XML_ATTR_FILE, getLineFilePath(line, wikiFolder)); + break; + case HomeToTOC.MD_LEVEL3: + if (currentPart != null && currentSubPart != null) { currentPart.appendChild(currentSubPart); } + currentSubPart = doc.createElement(HomeToTOC.XML_ELT_SUBPART); + currentSubPart.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); + currentSubPart.setAttribute(HomeToTOC.XML_ATTR_FILE, getLineFilePath(line, wikiFolder)); + break; + case HomeToTOC.MD_LEVEL4: + Element chapterElt = doc.createElement(HomeToTOC.XML_ELT_CHAPTER); + chapterElt.setAttribute(HomeToTOC.XML_ATTR_NAME, getLineTitle(line)); + chapterElt.setAttribute(HomeToTOC.XML_ATTR_FILE, getLineFilePath(line, wikiFolder)); + if (currentSubPart != null) { currentSubPart.appendChild(chapterElt); } + break; + default: + break; + } } - - doc.appendChild(root); - saveDocument(doc, savePath); - + + doc.appendChild(root); + saveDocument(doc, savePath); + } catch (IOException e) { e.printStackTrace(); - } + } } - + + /** + * Creates the document. + * + * @return the document + */ private static Document createDocument() { - Document doc = null; - - try { + Document doc = null; + + try { DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); - DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); - doc = documentBuilder.newDocument(); - } catch(Exception e) { + DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); + doc = documentBuilder.newDocument(); + } catch (Exception e) { e.printStackTrace(); } - - return doc; + + return doc; } - - private static void saveDocument(Document doc, String xmlFilePath) { - TransformerFactory transformerFactory = TransformerFactory.newInstance(); - Transformer transformer = null; - try { + /** + * Save document. + * + * @param doc + * the doc + * @param xmlFilePath + * the xml file path + */ + private static void saveDocument(final Document doc, final String xmlFilePath) { + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = null; + + try { transformer = transformerFactory.newTransformer(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } - - DOMSource domSource = new DOMSource(doc); - StreamResult streamResult = new StreamResult(new File(xmlFilePath)); - try { - transformer.transform(domSource, streamResult); + DOMSource domSource = new DOMSource(doc); + StreamResult streamResult = new StreamResult(new File(xmlFilePath)); + + try { + if (transformer != null) { transformer.transform(domSource, streamResult); } } catch (TransformerException e) { e.printStackTrace(); } - System.out.println("Done saving XML File"); + System.out.println("Done saving XML File"); } - - - // From a line of the Home.md file (e.g. ## [Home](Home)), computes the header level of the line - // or whether it is an empty line. - private static int getLineHeader(String line) { - if(line.startsWith("## ")) { - return HomeToTOC.MD_LEVEL2; - } - - Pattern patternEnum = Pattern.compile("^(\\d+.*)"); - Matcher matcher = patternEnum.matcher(line); - if(matcher.matches()) { - return HomeToTOC.MD_LEVEL3; - } - - Pattern patternEnumLevel2 = Pattern.compile("^(\\s\\s\\d+.*|\\t\\d+.*)"); - Matcher matcherLevel2 = patternEnumLevel2.matcher(line); - if(matcherLevel2.matches()) { - return HomeToTOC.MD_LEVEL4; - } - - Pattern patternWhiteSpace = Pattern.compile("[\\s|\\t|\\n]*"); - Matcher matcherSWhite = patternWhiteSpace.matcher(line); - if(matcherSWhite.matches()) { - return HomeToTOC.MD_LEVEL0; - } - + + // From a line of the Home.md file (e.g. ## [Home](Home)), computes the header level of the line + /** + * Gets the line header. + * + * @param line + * the line + * @return the line header + */ + // or whether it is an empty line. + private static int getLineHeader(final String line) { + if (line.startsWith("## ")) return HomeToTOC.MD_LEVEL2; + + Pattern patternEnum = Pattern.compile("^(\\d+.*)"); + Matcher matcher = patternEnum.matcher(line); + if (matcher.matches()) return HomeToTOC.MD_LEVEL3; + + Pattern patternEnumLevel2 = Pattern.compile("^(\\s\\s\\d+.*|\\t\\d+.*)"); + Matcher matcherLevel2 = patternEnumLevel2.matcher(line); + if (matcherLevel2.matches()) return HomeToTOC.MD_LEVEL4; + + Pattern patternWhiteSpace = Pattern.compile("[\\s|\\t|\\n]*"); + Matcher matcherSWhite = patternWhiteSpace.matcher(line); + if (matcherSWhite.matches()) return HomeToTOC.MD_LEVEL0; + return HomeToTOC.MD_LEVEL_ERR; } // From any line such as: ## [Introduction](Overview) - // returns the title, i.e. the string between brackets (Introduction here) + // returns the title, i.e. the string between brackets (Introduction here) // - // ## [Introduction](Overview) -----> Introduction - private static String getLineTitle(String line) throws IOException { - if( line.contains("[")) { - int indexBegin = line.indexOf("["); - int indexEnd = line.lastIndexOf("]"); - - return line.substring(indexBegin+1, indexEnd); - } + /** + * Gets the line title. + * + * @param line + * the line + * @return the line title + * @throws IOException + * Signals that an I/O exception has occurred. + */ + // ## [Introduction](Overview) -----> Introduction + private static String getLineTitle(final String line) throws IOException { + if (line.contains("[")) { + int indexBegin = line.indexOf("["); + int indexEnd = line.lastIndexOf("]"); + + return line.substring(indexBegin + 1, indexEnd); + } return line; } - + // From any line such as: ## [Introduction](Overview) - // returns the file name, i.e. the string between parentheses (Overview here) + // returns the file name, i.e. the string between parentheses (Overview here) // - // ## [Introduction](Overview) -----> Overview - private static String getLineFile(String line) { - if( line.contains("[")) { - int indexEndTitle = line.lastIndexOf("]"); - String endLine = line.substring(indexEndTitle+1,line.length()); - - int indexBegin = endLine.indexOf("("); - int indexEnd = endLine.lastIndexOf(")"); - - return endLine.substring(indexBegin+1, indexEnd); - } + /** + * Gets the line file. + * + * @param line + * the line + * @return the line file + */ + // ## [Introduction](Overview) -----> Overview + private static String getLineFile(final String line) { + if (line.contains("[")) { + int indexEndTitle = line.lastIndexOf("]"); + String endLine = line.substring(indexEndTitle + 1); + + int indexBegin = endLine.indexOf("("); + int indexEnd = endLine.lastIndexOf(")"); + + return endLine.substring(indexBegin + 1, indexEnd); + } return DEFAULT_FILE; } - + // From any line such as: ## [Introduction](Overview) - // returns the file relative path + // returns the file relative path // - // ## [Inspectors and Monitors](InspectorsAndMonitors) -----> References/PlatformDocumentation/RunningExperiments/InspectorsAndMonitors - private static String getLineFilePath(String line, String wikiFolder) { + // ## [Inspectors and Monitors](InspectorsAndMonitors) -----> + /** + * Gets the line file path. + * + * @param line + * the line + * @param wikiFolder + * the wiki folder + * @return the line file path + */ + // References/PlatformDocumentation/RunningExperiments/InspectorsAndMonitors + private static String getLineFilePath(final String line, final String wikiFolder) { String lineFile = getLineFile(line); - String lineFilePath = getRelativePathToWiki(lineFile,wikiFolder); - return lineFilePath; - } - - - private static String getRelativePathToWiki(String fileName, String wikiFolder) { + return getRelativePathToWiki(lineFile, wikiFolder); + } + + /** + * Gets the relative path to wiki. + * + * @param fileName + * the file name + * @param wikiFolder + * the wiki folder + * @return the relative path to wiki + */ + private static String getRelativePathToWiki(final String fileName, final String wikiFolder) { String resPath = ""; - + try (Stream stream = Files.find(Paths.get(wikiFolder), 5, - (path, attr) -> path.getFileName().toString().equals(fileName+HomeToTOC.MD_EXTENSION) )) { + (path, attr) -> (fileName + HomeToTOC.MD_EXTENSION).equals(path.getFileName().toString()))) { Optional val = stream.findFirst(); - String path = val.isPresent()?val.get().toString():""; - - // System.out.println(path); - - resPath = path.substring( (wikiFolder + File.separator).length(), path.length()-HomeToTOC.MD_EXTENSION.length()); + String path = val.isPresent() ? val.get().toString() : ""; + + // System.out.println(path); + + resPath = path.substring((wikiFolder + File.separator).length(), + path.length() - HomeToTOC.MD_EXTENSION.length()); } catch (IOException e) { - e.printStackTrace(); - } - return resPath; + e.printStackTrace(); + } + return resPath; } - - - public static void main(String[] args) { + + /** + * The main method. + * + * @param args + * the arguments + */ + public static void main(final String[] args) { final String tocMDFile = Constants.TOC_SIDEBAR_FILE; - - HomeToTOC.md2toc(tocMDFile,Constants.TOC_FILE_PATH,Constants.WIKI_FOLDER); - + + HomeToTOC.md2toc(tocMDFile, Constants.TOC_FILE_PATH, Constants.WIKI_FOLDER); + String s = "InspectorsAndMonitors"; - - System.out.println(getRelativePathToWiki(s,Constants.WIKI_FOLDER)); - + + System.out.println(getRelativePathToWiki(s, Constants.WIKI_FOLDER)); + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFBlock.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFBlock.java index 31091ec526..0ca71a4bb4 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFBlock.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFBlock.java @@ -1,18 +1,12 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFBlock.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -20,181 +14,184 @@ import msi.gama.ext.kabeja.dxf.helpers.Point; - /** * @author entities; + + /** The doc. */ + private DXFDocument doc; + + /** + * + */ + public DXFBlock() { + this.entities = new ArrayList<>(); + this.referencePoint = new Point(); + } + + /** + * Gets the bounds. + * + * @return the bounds + */ + public Bounds getBounds() { + // first set the own point + Bounds bounds = new Bounds(); + Iterator i = entities.iterator(); + + if (i.hasNext()) { + while (i.hasNext()) { + DXFEntity entity = i.next(); + Bounds b = entity.getBounds(); + + if (b.isValid()) { bounds.addToBounds(b); } + } + } else { + bounds.setValid(false); + } + + return bounds; + } + + /** + * @return Returns the description. + */ + public String getDescription() { return description; } + + /** + * @param description + * The description to set. + */ + public void setDescription(final String description) { this.description = description; } + + /** + * @return Returns the p. + */ + public Point getReferencePoint() { return referencePoint; } + + /** + * @param p + * The p to set. + */ + public void setReferencePoint(final Point p) { this.referencePoint = p; } + + /** + * Adds the DXF entity. + * + * @param entity + * the entity + */ + public void addDXFEntity(final DXFEntity entity) { + entities.add(entity); + } + + /** + * + * @return a iterator over all entities of this block + */ + public Iterator getDXFEntitiesIterator() { return entities.iterator(); } + + /** + * @return Returns the layerID. + */ + public String getLayerID() { return layerID; } + + /** + * @param layerID + * The layerID to set. + */ + public void setLayerID(final String layerID) { this.layerID = layerID; } + + /** + * @return Returns the name. + */ + public String getName() { return name; } + + /** + * @param name + * The name to set. + */ + public void setName(final String name) { this.name = name; } + + /** + * @param doc + * The doc to set. + */ + public void setDXFDocument(final DXFDocument doc) { + this.doc = doc; + + Iterator i = entities.iterator(); + + while (i.hasNext()) { + DXFEntity entity = (DXFEntity) i.next(); + entity.setDXFDocument(doc); + } + } + + /** + * + * @return the parent document + */ + public DXFDocument getDXFDocument() { return this.doc; } + + /** + * Gets the length. + * + * @return the length + */ + public double getLength() { + double length = 0; + Iterator i = entities.iterator(); + + while (i.hasNext()) { + DXFEntity entity = (DXFEntity) i.next(); + length += entity.getLength(); + } + + return length; + } + + /** + * Gets the + * + * @see DXFEntity with the specified ID. + * @param id + * of the + * @see DXFEntity + * @return the + * @see DXFEntity with the specified ID or null if there is no + * @see DXFEntity with the specified ID + */ + public DXFEntity getDXFEntityByID(final String id) { + DXFEntity entity = null; + Iterator i = this.entities.iterator(); + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + + if (e.getID().equals(id)) return e; + } + + return entity; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDimensionStyle.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDimensionStyle.java index 9150a59cfc..d1cb3bcb50 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDimensionStyle.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDimensionStyle.java @@ -1,208 +1,396 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFDimensionStyle.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.HashMap; import java.util.Iterator; - /** * @author properties = new HashMap<>(); + + /** The flags. */ + private int flags = 0; + + /** The name. */ + private String name = ""; + + /** + * Sets the property. + * + * @param key + * the key + * @param value + * the value + */ + public void setProperty(final String key, final String value) { + properties.put(key, value); + } + + /** + * Checks for property. + * + * @param name + * the name + * @return true, if successful + */ + public boolean hasProperty(final String name) { + return properties.containsKey(name); + } + + /** + * Gets the property. + * + * @param name + * the name + * @return the property + */ + public String getProperty(final String name) { + return properties.get(name); + } + + /** + * Gets the integer property. + * + * @param name + * the name + * @return the integer property + */ + public int getIntegerProperty(final String name) { + String value = properties.get(name); + + return Integer.parseInt(value); + } + + /** + * Gets the integer property. + * + * @param name + * the name + * @param defaultValue + * the default value + * @return the integer property + */ + public int getIntegerProperty(final String name, final int defaultValue) { + if (hasProperty(name)) { + String value = properties.get(name); + + return Integer.parseInt(value); + } + return defaultValue; + } + + /** + * Gets the double property. + * + * @param name + * the name + * @return the double property + */ + public double getDoubleProperty(final String name) { + String value = properties.get(name); + + return Double.parseDouble(value); + } + + /** + * Gets the double property. + * + * @param name + * the name + * @param defaultValue + * the default value + * @return the double property + */ + public double getDoubleProperty(final String name, final double defaultValue) { + if (hasProperty(name)) { + String value = properties.get(name); + + return Double.parseDouble(value); + } + return defaultValue; + } + + /** + * Gets the boolean property. + * + * @param name + * the name + * @return the boolean property + */ + public boolean getBooleanProperty(final String name) { + String value = properties.get(name); + + if ("1".equals(value)) return true; + return false; + } + + /** + * Gets the boolean property. + * + * @param name + * the name + * @param defaultValue + * the default value + * @return the boolean property + */ + public boolean getBooleanProperty(final String name, final boolean defaultValue) { + if (!hasProperty(name)) return defaultValue; + String value = properties.get(name); + + if ("1".equals(value)) return true; + return false; + } + + /** + * Gets the property iterator. + * + * @return the property iterator + */ + public Iterator getPropertyIterator() { return properties.values().iterator(); } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { return name; } + + /** + * Sets the name. + * + * @param name + * the new name + */ + public void setName(final String name) { this.name = name; } + + /** + * Sets the flags. + * + * @param flags + * the new flags + */ + public void setFlags(final int flags) { this.flags = flags; } + + /** + * Gets the flags. + * + * @return the flags + */ + public int getFlags() { return flags; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDocument.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDocument.java index 044dc2eb68..618b2d2f57 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDocument.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFDocument.java @@ -1,18 +1,12 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFDocument.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -25,402 +19,556 @@ import msi.gama.ext.kabeja.dxf.objects.DXFDictionary; import msi.gama.ext.kabeja.dxf.objects.DXFObject; - /** * @author search in the dictionaries - return this.rootDictionary.getDXFObjectByID(id); - } - - /** - * Gets the - * - * @see DXFEntity with the specified ID. - * @param id - * of the - * @see DXFEntity - * @return the - * @see DXFEntity with the specified ID or null if there is no - * @see DXFEntity with the specified ID - */ - public DXFEntity getDXFEntityByID(String id) { - DXFEntity entity = null; - Iterator i = this.getDXFLayerIterator(); - - while (i.hasNext()) { - DXFLayer layer = (DXFLayer) i.next(); - - if ((entity = layer.getDXFEntityByID(id)) != null) { - return entity; - } - } - - i = this.getDXFBlockIterator(); - - while (i.hasNext()) { - DXFBlock block = (DXFBlock) i.next(); - - if ((entity = block.getDXFEntityByID(id)) != null) { - return entity; - } - } - - return entity; - } - - /** - * Adds a DXFHatchPattern to the document. - * - * @param pattern - */ - public void addDXFHatchPattern(DXFHatchPattern pattern) { - this.patterns.put(pattern.getID(), pattern); - } - - /** - * - * @return java.util.Iterator over all DXFHatchPattern of the document - */ - public Iterator getDXFHatchPatternIterator() { - return this.patterns.values().iterator(); - } - - /** - * - * @param ID - * of the pattern (also called pattern name) - * @return the DXFHatchPattern or null - */ - public DXFHatchPattern getDXFHatchPattern(String id) { - return (DXFHatchPattern) this.patterns.get(id); - } + + /** The property encoding. */ + public static String PROPERTY_ENCODING = "encoding"; + + /** The Constant DEFAULT_MARGIN. */ + public static final double DEFAULT_MARGIN = 5; + + /** The layers. */ + private final Hashtable layers = new Hashtable<>(); + + /** The blocks. */ + private final Hashtable blocks = new Hashtable<>(); + + /** The line types. */ + private final HashMap lineTypes = new HashMap<>(); + + /** The dimension styles. */ + private final HashMap dimensionStyles = new HashMap<>(); + + /** The text styles. */ + private final HashMap textStyles = new HashMap<>(); + + // the user coordinate systems + /** The properties. */ + // private Hashtable ucs = new Hashtable(); + private final Hashtable properties = new Hashtable<>(); + + /** The viewports. */ + private final List viewports = new ArrayList<>(); + + /** The bounds. */ + private Bounds bounds = new Bounds(); + + /** The header. */ + // private double margin; + private DXFHeader header = new DXFHeader(); + + /** The objects. */ + private final HashMap objects = new HashMap<>(); + + /** The patterns. */ + private final HashMap patterns = new HashMap<>(); + + /** The views. */ + private final List views = new ArrayList<>(); + + /** The root dictionary. */ + private DXFDictionary rootDictionary = new DXFDictionary(); + + /** + * Instantiates a new DXF document. + */ + public DXFDocument() { + // the defalut layer + DXFLayer defaultLayer = new DXFLayer(); + defaultLayer.setDXFDocument(this); + defaultLayer.setName(DXFConstants.DEFAULT_LAYER); + this.layers.put(DXFConstants.DEFAULT_LAYER, defaultLayer); + + // setup the margin + // this.margin = DEFAULT_MARGIN; + + // setup the root Dictionary + this.rootDictionary = new DXFDictionary(); + this.rootDictionary.setDXFDocument(this); + } + + /** + * Adds the DXF layer. + * + * @param layer + * the layer + */ + public void addDXFLayer(final DXFLayer layer) { + layer.setDXFDocument(this); + layers.put(layer.getName(), layer); + } + + /** + * + * Returns the specified layer. + * + * @param key + * The layer id + * @return the layer or if not found the default layer (layer "0") + */ + public DXFLayer getDXFLayer(final String key) { + if (this.layers.containsKey(key)) return layers.get(key); + + // retun the default layer + if (this.layers.containsKey(DXFConstants.DEFAULT_LAYER)) return layers.get(DXFConstants.DEFAULT_LAYER); + DXFLayer layer = new DXFLayer(); + layer.setName(DXFConstants.DEFAULT_LAYER); + this.addDXFLayer(layer); + + return layer; + } + + /** + * Returns true if the document contains the specified layer. + * + * @param layerName + * the layer name + * @return true - if the document contains the layer, otherwise false + */ + public boolean containsDXFLayer(final String layerName) { + return this.layers.containsKey(layerName); + } + + /** + * + * @return the iterator over all DXFLayer of this document + */ + public Iterator getDXFLayerIterator() { return layers.values().iterator(); } + + /** + * Adds the DXF line type. + * + * @param ltype + * the ltype + */ + public void addDXFLineType(final DXFLineType ltype) { + lineTypes.put(ltype.getName(), ltype); + } + + /** + * Gets the DXF line type. + * + * @param name + * the name + * @return the DXF line type + */ + public DXFLineType getDXFLineType(final String name) { + return lineTypes.get(name); + } + + /** + * + * @return the iterator over all DXFLineTypes + */ + public Iterator getDXFLineTypeIterator() { return lineTypes.values().iterator(); } + + /** + * Adds the DXF entity. + * + * @param entity + * the entity + */ + public void addDXFEntity(final DXFEntity entity) { + entity.setDXFDocument(this); + + DXFLayer layer = this.getDXFLayer(entity.getLayerName()); + layer.addDXFEntity(entity); + } + + /** + * Adds the DXF block. + * + * @param block + * the block + */ + public void addDXFBlock(final DXFBlock block) { + block.setDXFDocument(this); + this.blocks.put(block.getName(), block); + } + + /** + * Gets the DXF block. + * + * @param name + * the name + * @return the DXF block + */ + public DXFBlock getDXFBlock(final String name) { + return blocks.get(name); + } + + /** + * + * @return the iterator over all DXFBlocks + */ + public Iterator getDXFBlockIterator() { return blocks.values().iterator(); } + + /** + * Sets the property. + * + * @param key + * the key + * @param value + * the value + */ + public void setProperty(final String key, final String value) { + this.properties.put(key, value); + } + + /** + * Gets the property. + * + * @param key + * the key + * @return the property + */ + public String getProperty(final String key) { + if (properties.contains(key)) return properties.get(key); + + return null; + } + + /** + * Checks for property. + * + * @param key + * the key + * @return true, if successful + */ + public boolean hasProperty(final String key) { + return this.properties.containsKey(key); + } + + /** + * Returns the bounds of this document + * + * @return + */ + public Bounds getBounds() { + this.bounds = new Bounds(); + + Enumeration e = this.layers.elements(); + + while (e.hasMoreElements()) { + DXFLayer layer = (DXFLayer) e.nextElement(); + + if (!layer.isFrozen()) { + Bounds b = layer.getBounds(); + + if (b.isValid()) { this.bounds.addToBounds(b); } + } + } + + return bounds; + } + + /** + * Returns the bounds of this document + * + * @return + */ + public Bounds getBounds(final boolean onModelspace) { + Bounds bounds = new Bounds(); + + Enumeration e = this.layers.elements(); + + while (e.hasMoreElements()) { + DXFLayer layer = (DXFLayer) e.nextElement(); + + if (!layer.isFrozen()) { + Bounds b = layer.getBounds(onModelspace); + + if (b.isValid()) { bounds.addToBounds(b); } + } + } + + return bounds; + } + + /** + * @deprecated use getBounds().getHeight() instead + * @return + */ + @Deprecated + public double getHeight() { return this.bounds.getHeight(); } + + /** + * @deprecated use getBounds().getWidth() instead + * @return + */ + @Deprecated + public double getWidth() { return this.bounds.getWidth(); } + + /** + * Gets the DXF header. + * + * @return the DXF header + */ + public DXFHeader getDXFHeader() { return this.header; } + + /** + * Sets the DXF header. + * + * @param header + * the new DXF header + */ + public void setDXFHeader(final DXFHeader header) { this.header = header; } + + /** + * Adds the DXF dimension style. + * + * @param style + * the style + */ + public void addDXFDimensionStyle(final DXFDimensionStyle style) { + this.dimensionStyles.put(style.getName(), style); + } + + /** + * Gets the DXF dimension style. + * + * @param name + * the name + * @return the DXF dimension style + */ + public DXFDimensionStyle getDXFDimensionStyle(final String name) { + return this.dimensionStyles.get(name); + } + + /** + * Gets the DXF dimension style iterator. + * + * @return the DXF dimension style iterator + */ + public Iterator getDXFDimensionStyleIterator() { return this.dimensionStyles.values().iterator(); } + + /** + * Adds the DX style. + * + * @param style + * the style + */ + public void addDXStyle(final DXFStyle style) { + this.textStyles.put(style.getName(), style); + } + + /** + * Gets the DXF style. + * + * @param name + * the name + * @return the DXF style + */ + public DXFStyle getDXFStyle(final String name) { + return this.textStyles.get(name); + } + + /** + * Gets the DXF style iterator. + * + * @return the DXF style iterator + */ + public Iterator getDXFStyleIterator() { return this.textStyles.values().iterator(); } + + /** + * Removes the DXF layer. + * + * @param id + * the id + */ + public void removeDXFLayer(final String id) { + this.layers.remove(id); + } + + /** + * Adds the DXF viewport. + * + * @param viewport + * the viewport + */ + public void addDXFViewport(final DXFViewport viewport) { + this.viewports.add(viewport); + } + + /** + * Gets the DXF viewport iterator. + * + * @return the DXF viewport iterator + */ + public Iterator getDXFViewportIterator() { return this.viewports.iterator(); } + + /** + * Removes the DXF viewport. + * + * @param viewport + * the viewport + */ + public void removeDXFViewport(final DXFViewport viewport) { + this.viewports.remove(viewport); + } + + /** + * Removes the DXF viewport. + * + * @param index + * the index + */ + public void removeDXFViewport(final int index) { + this.viewports.remove(index); + } + + /** + * Adds the DXF view. + * + * @param view + * the view + */ + public void addDXFView(final DXFView view) { + this.views.add(view); + } + + /** + * Gets the DXF view iterator. + * + * @return the DXF view iterator + */ + public Iterator getDXFViewIterator() { return this.views.iterator(); } + + /** + * Adds the DXF object. + * + * @param obj + * the obj + */ + @SuppressWarnings ("unchecked") + public void addDXFObject(final DXFObject obj) { + // look if the object goes in a dictionary + DXFDictionary d = this.rootDictionary.getDXFDictionaryForID(obj.getID()); + + if (d != null) { + d.putDXFObject(obj); + } else { + // is not bound to a dictionary + HashMap type = null; + + if (this.objects.containsKey(obj.getObjectType())) { + type = (HashMap) objects.get(obj.getObjectType()); + } else { + type = new HashMap<>(); + this.objects.put(obj.getObjectType(), type); + } + + type.put(obj.getID(), obj); + } + } + + /** + * Returns the root dictionary. + * + * @return the root DXFDictionray + */ + public DXFDictionary getRootDXFDictionary() { return this.rootDictionary; } + + /** + * Sets the root DXF dictionary. + * + * @param root + * the new root DXF dictionary + */ + public void setRootDXFDictionary(final DXFDictionary root) { this.rootDictionary = root; } + + /** + * Gets the DXF objects by type. + * + * @param type + * the type + * @return the DXF objects by type + */ + public List getDXFObjectsByType(final String type) { + @SuppressWarnings ("unchecked") HashMap objecttypes = + (HashMap) this.objects.get(type); + return new ArrayList<>(objecttypes.values()); + } + + /** + * + * @param id, + * the ID of the object + * @return the object + */ + public DXFObject getDXFObjectByID(final String id) { + Iterator i = this.objects.values().iterator(); + + while (i.hasNext()) { + HashMap map = (HashMap) i.next(); + Object obj; + + if ((obj = map.get(id)) != null) return (DXFObject) obj; + } + + // Nothing found --> search in the dictionaries + return this.rootDictionary.getDXFObjectByID(id); + } + + /** + * Gets the + * + * @see DXFEntity with the specified ID. + * @param id + * of the + * @see DXFEntity + * @return the + * @see DXFEntity with the specified ID or null if there is no + * @see DXFEntity with the specified ID + */ + public DXFEntity getDXFEntityByID(final String id) { + DXFEntity entity = null; + Iterator i = this.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer layer = (DXFLayer) i.next(); + + if ((entity = layer.getDXFEntityByID(id)) != null) return entity; + } + + i = this.getDXFBlockIterator(); + + while (i.hasNext()) { + DXFBlock block = (DXFBlock) i.next(); + + if ((entity = block.getDXFEntityByID(id)) != null) return entity; + } + + return entity; + } + + /** + * Adds a DXFHatchPattern to the document. + * + * @param pattern + */ + public void addDXFHatchPattern(final DXFHatchPattern pattern) { + this.patterns.put(pattern.getID(), pattern); + } + + /** + * + * @return java.util.Iterator over all DXFHatchPattern of the document + */ + public Iterator getDXFHatchPatternIterator() { return this.patterns.values().iterator(); } + + /** + * + * @param ID + * of the pattern (also called pattern name) + * @return the DXFHatchPattern or null + */ + public DXFHatchPattern getDXFHatchPattern(final String id) { + return this.patterns.get(id); + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFEllipse.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFEllipse.java index 04f3c65494..a5f8468d21 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFEllipse.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFEllipse.java @@ -1,7 +1,12 @@ -/* - * Created on Jul 15, 2004 +/******************************************************************************************************* * - */ + * DXFEllipse.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import msi.gama.ext.kabeja.dxf.helpers.Point; @@ -9,235 +14,306 @@ import msi.gama.ext.kabeja.math.MathUtils; import msi.gama.ext.kabeja.math.ParametricPlane; - /** * @author boundaries = new ArrayList<>(); + // + // /** The patterns. */ + // private final List patterns = new ArrayList(); + + /** The pattern ID. */ + private String patternID = ""; + + /** The pattern scale. */ + private double patternScale; + + /** + * Instantiates a new DXF hatch. + */ + public DXFHatch() {} + + /** + * @return Returns the associativityFlag. + */ + public int getAssociativityFlag() { return associativityFlag; } + + /** + * @param associativityFlag + * The associativityFlag to set. + */ + public void setAssociativityFlag(final int associativityFlag) { this.associativityFlag = associativityFlag; } + + /** + * @return Returns the boundaryAnnotation. + */ + public boolean isBoundaryAnnotation() { return boundaryAnnotation; } + + /** + * @param boundaryAnnotation + * The boundaryAnnotation to set. + */ + public void setBoundaryAnnotation(final boolean boundaryAnnotation) { + this.boundaryAnnotation = boundaryAnnotation; + } + + /** + * @return Returns the boundaryPathCount. + */ + public int getBoundaryPathCount() { return boundaryPathCount; } + + /** + * @param boundaryPathCount + * The boundaryPathCount to set. + */ + public void setBoundaryPathCount(final int boundaryPathCount) { this.boundaryPathCount = boundaryPathCount; } + + /** + * @return Returns the definationLinesCount. + */ + public int getDefinationLinesCount() { return definationLinesCount; } + + /** + * @param definationLinesCount + * The definationLinesCount to set. + */ + public void setDefinationLinesCount(final int definationLinesCount) { + this.definationLinesCount = definationLinesCount; + } + + /** + * @return Returns the degenerateBoundaryPathCount. + */ + public int getDegenerateBoundaryPathCount() { return degenerateBoundaryPathCount; } + + /** + * @param degenerateBoundaryPathCount + * The degenerateBoundaryPathCount to set. + */ + public void setDegenerateBoundaryPathCount(final int degenerateBoundaryPathCount) { + this.degenerateBoundaryPathCount = degenerateBoundaryPathCount; + } + + /** + * @return Returns the gradientHatch. + */ + public boolean isGradientHatch() { return gradientHatch; } + + /** + * @param gradientHatch + * The gradientHatch to set. + */ + public void setGradientHatch(final boolean gradientHatch) { this.gradientHatch = gradientHatch; } + + /** + * @return Returns the hatchStyle. + */ + public int getHatchStyle() { return hatchStyle; } + + /** + * @param hatchStyle + * The hatchStyle to set. + */ + public void setHatchStyle(final int hatchStyle) { this.hatchStyle = hatchStyle; } + + /** + * @return Returns the name. + */ + public String getName() { return name; } + + /** + * @param name + * The name to set. + */ + public void setName(final String name) { this.name = name; } + + /** + * @return Returns the offsetVector. + */ + public double getOffsetVector() { return offsetVector; } + + /** + * @param offsetVector + * The offsetVector to set. + */ + public void setOffsetVector(final double offsetVector) { this.offsetVector = offsetVector; } + + /** + * @return Returns the patternAngle. + */ + public double getPatternAngle() { return patternAngle; } + + /** + * @param patternAngle + * The patternAngle to set. + */ + public void setPatternAngle(final double patternAngle) { this.patternAngle = patternAngle; } + + /** + * @return Returns the patternDouble. + */ + public boolean isPatternDouble() { return patternDouble; } + + /** + * @param patternDouble + * The patternDouble to set. + */ + public void setPatternDouble(final boolean patternDouble) { this.patternDouble = patternDouble; } + + /** + * @return Returns the patternScaleSpacing. + */ + public double getPatternScaleSpacing() { return patternScaleSpacing; } + + /** + * @param patternScaleSpacing + * The patternScaleSpacing to set. + */ + public void setPatternScaleSpacing(final double patternScaleSpacing) { + this.patternScaleSpacing = patternScaleSpacing; + } + + /** + * @return Returns the patternType. + */ + public int getPatternType() { return patternType; } + + /** + * @param patternType + * The patternType to set. + */ + public void setPatternType(final int patternType) { this.patternType = patternType; } + + /** + * @return Returns the pixelSize. + */ + public double getPixelSize() { return pixelSize; } + + /** + * @param pixelSize + * The pixelSize to set. + */ + public void setPixelSize(final double pixelSize) { this.pixelSize = pixelSize; } + + /** + * @return Returns the seedPointCount. + */ + public int getSeedPointCount() { return seedPointCount; } + + /** + * @param seedPointCount + * The seedPointCount to set. + */ + public void setSeedPointCount(final int seedPointCount) { this.seedPointCount = seedPointCount; } + + /** + * @return Returns the solid. + */ + public boolean isSolid() { return this.flags == 1; } + + /** + * @param solid + * The solid to set. + */ + public void setSolid(final boolean solid) { + this.flags = 1; + // this. solid = solid; + } + + /** + * Adds the boundary loop. + * + * @param loop + * the loop + */ + public void addBoundaryLoop(final HatchBoundaryLoop loop) { + this.boundaries.add(loop); + } + + /** + * Gets the boundary loops. + * + * @return the boundary loops + */ + public Iterator getBoundaryLoops() { return this.boundaries.iterator(); } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.dxf.DXFEntity#getBounds() + */ + @Override + public Bounds getBounds() { + Bounds bounds = new Bounds(); + Iterator i = this.boundaries.iterator(); + + while (i.hasNext()) { + HatchBoundaryLoop loop = (HatchBoundaryLoop) i.next(); + Bounds b = loop.getBounds(); + + if (b.isValid()) { bounds.addToBounds(b); } + } + + return bounds; + } + + /** + * @return Returns the elevationPoint. + */ + public Point getElevationPoint() { return elevationPoint; } + + /** + * @param elevationPoint + * The elevationPoint to set. + */ + public void setElevationPoint(final Point elevationPoint) { this.elevationPoint = elevationPoint; } + + @Override + public String getType() { return DXFConstants.ENTITY_TYPE_HATCH; } + + /** + * @return Returns the ID of the pattern (also called pattern name). + */ + public String getDXFHatchPatternID() { return this.patternID; } + + /** + * @param patternID + * The patternID to set. + */ + public void setDXFHatchPatternID(final String patternID) { this.patternID = patternID; } + + @Override + public double getLength() { return 0; } + + /** + * Gets the pattern scale. + * + * @return the pattern scale + */ + public double getPatternScale() { return patternScale; } + + /** + * Sets the pattern scale. + * + * @param patternScale + * the new pattern scale + */ + public void setPatternScale(final double patternScale) { this.patternScale = patternScale; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHatchPattern.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHatchPattern.java index 89fe9ab417..bac4b0a6ba 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHatchPattern.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHatchPattern.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFHatchPattern.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -21,7 +16,6 @@ import msi.gama.ext.kabeja.dxf.helpers.HatchLineFamily; - /** * This class represent a single line family of a hatch pattern set. * @@ -29,63 +23,71 @@ * */ public class DXFHatchPattern { - private static int idCount = 0; - private String id = null; - private List patterns = new ArrayList(); - private DXFHatch hatch; + + /** The id count. */ + private static int idCount = 0; + + /** The id. */ + private String id = null; + + /** The patterns. */ + private final List patterns = new ArrayList<>(); + + /** The hatch. */ + private DXFHatch hatch; - /** - * @return Returns the id. - */ - public String getID() { - if (this.id == null) { - this.id = "HATCH_PATTERN_ID_" + DXFHatchPattern.idCount; - DXFHatchPattern.idCount++; - } + /** + * @return Returns the id. + */ + public String getID() { + if (this.id == null) { + this.id = "HATCH_PATTERN_ID_" + DXFHatchPattern.idCount; + DXFHatchPattern.idCount++; + } - return id; - } + return id; + } - /** - * @param id - * The id to set. - */ - public void setID(String id) { - this.id = id; - } + /** + * @param id + * The id to set. + */ + public void setID(final String id) { this.id = id; } - public void addLineFamily(HatchLineFamily pattern) { - patterns.add(pattern); - } + /** + * Adds the line family. + * + * @param pattern the pattern + */ + public void addLineFamily(final HatchLineFamily pattern) { + patterns.add(pattern); + } - public Iterator getLineFamilyIterator() { - return patterns.iterator(); - } + /** + * Gets the line family iterator. + * + * @return the line family iterator + */ + public Iterator getLineFamilyIterator() { return patterns.iterator(); } - /** - * The associated hatch for this pattern. - * - * @return Returns the hatch. - */ - public DXFHatch getDXFHatch() { - return this.hatch; - } + /** + * The associated hatch for this pattern. + * + * @return Returns the hatch. + */ + public DXFHatch getDXFHatch() { return this.hatch; } - /** - * The associated hatch for this pattern. - * - * @param hatch - * The hatch to set. - */ - public void setHatch(DXFHatch hatch) { - this.hatch = hatch; - } + /** + * The associated hatch for this pattern. + * + * @param hatch + * The hatch to set. + */ + public void setHatch(final DXFHatch hatch) { this.hatch = hatch; } - /** - * - * @return the count of the used line families - */ - public int getLineFamilyCount() { - return this.patterns.size(); - } + /** + * + * @return the count of the used line families + */ + public int getLineFamilyCount() { return this.patterns.size(); } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHeader.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHeader.java index 62667eacb3..562040b5cc 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHeader.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFHeader.java @@ -1,24 +1,18 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFHeader.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.Hashtable; import java.util.Iterator; - /** * @author 0)) { - return true; - } - - return false; - } - - /** - * Returns the global linetype scale factor. - * - * @return the global scalefactor - */ - public double getLinetypeScale() { - double gscale = 1.0; - - if (hasVariable("$LTSCALE")) { - gscale = getVariable("$LTSCALE").getDoubleValue("40"); - } - - return gscale; - } + + /** The variables. */ + private final Hashtable variables = new Hashtable<>(); + + /** + * Instantiates a new DXF header. + */ + public DXFHeader() {} + + /** + * Sets the variable. + * + * @param v the new variable + */ + public void setVariable(final DXFVariable v) { + variables.put(v.getName(), v); + } + + /** + * Checks for variable. + * + * @param name the name + * @return true, if successful + */ + public boolean hasVariable(final String name) { + return variables.containsKey(name); + } + + /** + * Gets the variable. + * + * @param name the name + * @return the variable + */ + public DXFVariable getVariable(final String name) { + return variables.get(name); + } + + /** + * Gets the varialbe iterator. + * + * @return the varialbe iterator + */ + public Iterator getVarialbeIterator() { return variables.values().iterator(); } + + /** + * Checks if is fill mode. + * + * @return true, if is fill mode + */ + public boolean isFillMode() { + if (hasVariable("$FILLMODE") && getVariable("$FILLMODE").getDoubleValue("70") > 0) return true; + + return false; + } + + /** + * Returns the global linetype scale factor. + * + * @return the global scalefactor + */ + public double getLinetypeScale() { + double gscale = 1.0; + + if (hasVariable("$LTSCALE")) { gscale = getVariable("$LTSCALE").getDoubleValue("40"); } + + return gscale; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFImage.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFImage.java index eb37501258..b0e211b435 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFImage.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFImage.java @@ -1,7 +1,13 @@ -/* - * Created on 28.06.2005 +/******************************************************************************************************* * - */ + * DXFImage.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -9,235 +15,238 @@ import msi.gama.ext.kabeja.dxf.helpers.Point; import msi.gama.ext.kabeja.dxf.objects.DXFImageDefObject; - /** * @author clipBoundary = new ArrayList<>(); + + /** The clipping. */ + protected boolean clipping = false; + + /** The rectangular clipping. */ + protected boolean rectangularClipping = false; + + /** The polygonal clipping. */ + protected boolean polygonalClipping = false; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.dxf.DXFEntity#getBounds() + */ + @Override + public Bounds getBounds() { + Bounds b = new Bounds(); + DXFImageDefObject imageDef = (DXFImageDefObject) this.doc.getDXFObjectByID(this.getImageDefObjectID()); + + if (imageDef != null) { + b.addToBounds(this.insertPoint); + b.addToBounds(insertPoint.getX() + imageSizeAlongU, insertPoint.getY() + imageSizeAlongV, + this.insertPoint.getZ()); + } else { + b.setValid(false); + } + + return b; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.dxf.DXFEntity#getType() + */ + @Override + public String getType() { return DXFConstants.ENTITY_TYPE_IMAGE; } + + /** + * Gets the insert point. + * + * @return the insert point + */ + public Point getInsertPoint() { return insertPoint; } + + /** + * Sets the insert point. + * + * @param p the new insert point + */ + public void setInsertPoint(final Point p) { this.insertPoint = p; } + + /** + * Sets the image def object ID. + * + * @param id the new image def object ID + */ + public void setImageDefObjectID(final String id) { this.imageDefID = id; } + + /** + * Gets the image def object ID. + * + * @return the image def object ID + */ + public String getImageDefObjectID() { return this.imageDefID; } + + /** + * @return Returns the imageSizeAlongU. + */ + public double getImageSizeAlongU() { return imageSizeAlongU; } + + /** + * @param imageSizeAlongU + * The imageSizeAlongU to set. + */ + public void setImageSizeAlongU(final double imageSizeAlongU) { this.imageSizeAlongU = imageSizeAlongU; } + + /** + * @return Returns the imageSizeAlongV. + */ + public double getImageSizeAlongV() { return imageSizeAlongV; } + + /** + * @param imageSizeAlongV + * The imageSizeAlongV to set. + */ + public void setImageSizeAlongV(final double imageSizeAlongV) { this.imageSizeAlongV = imageSizeAlongV; } + + /** + * @return Returns the vectorU. + */ + public Point getVectorU() { return vectorU; } + + /** + * @param vectorU + * The vectorU to set. + */ + public void setVectorU(final Point vectorU) { this.vectorU = vectorU; } + + /** + * @return Returns the vectorV. + */ + public Point getVectorV() { return vectorV; } + + /** + * @param vectorV + * The vectorV to set. + */ + public void setVectorV(final Point vectorV) { this.vectorV = vectorV; } + + /** + * @return Returns the brightness. + */ + public double getBrightness() { return brightness; } + + /** + * @param brightness + * The brightness to set. + */ + public void setBrightness(final double brightness) { this.brightness = brightness; } + + /** + * @return Returns the clipping. + */ + public boolean isClipping() { return clipping; } + + /** + * @param clipping + * The clipping to set. + */ + public void setClipping(final boolean clipping) { this.clipping = clipping; } + + /** + * @return Returns the contrast. + */ + public double getContrast() { return contrast; } + + /** + * @param contrast + * The contrast to set. + */ + public void setContrast(final double contrast) { this.contrast = contrast; } + + /** + * @return Returns the fade. + */ + public double getFade() { return fade; } + + /** + * @param fade + * The fade to set. + */ + public void setFade(final double fade) { this.fade = fade; } + + /** + * @return Returns the clipBoundary. + */ + public ArrayList getClipBoundary() { return clipBoundary; } + + /** + * Adds the clipping point. + * + * @param p the p + */ + public void addClippingPoint(final Point p) { + clipBoundary.add(p); + } + + /** + * @return Returns the polygonalClipping. + */ + public boolean isPolygonalClipping() { return polygonalClipping; } + + /** + * @param polygonalClipping + * The polygonalClipping to set. + */ + public void setPolygonalClipping(final boolean polygonalClipping) { + this.polygonalClipping = polygonalClipping; + this.rectangularClipping = !polygonalClipping; + } + + /** + * @return Returns the rectangularClipping. + */ + public boolean isRectangularClipping() { return rectangularClipping; } + + /** + * @param rectangularClipping + * The rectangularClipping to set. + */ + public void setRectangularClipping(final boolean rectangularClipping) { + this.rectangularClipping = rectangularClipping; + this.polygonalClipping = !rectangularClipping; + } + + @Override + public double getLength() { return 0; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLayer.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLayer.java index 053d9752c8..f0a37cf46b 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLayer.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLayer.java @@ -1,18 +1,12 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFLayer.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -21,240 +15,298 @@ import java.util.Iterator; import java.util.List; - /** * @author list = new ArrayList<>(); + list.add(entity); + entities.put(entity.getType(), list); + } + } + + /** + * Removes the DXF entity. + * + * @param entity + * the entity + */ + public void removeDXFEntity(final DXFEntity entity) { + if (entities.containsKey(entity.getType())) { + ArrayList list = entities.get(entity.getType()); + list.remove(entity); + + if (list.isEmpty()) { entities.remove(entity.getType()); } + } + } + + /** + * Sets the DXF document. + * + * @param doc + * the new DXF document + */ + public void setDXFDocument(final DXFDocument doc) { this.doc = doc; } + + /** + * Gets the DXF document. + * + * @return the DXF document + */ + public DXFDocument getDXFDocument() { return this.doc; } + + /** + * Gets the bounds. + * + * @return the bounds + */ + public Bounds getBounds() { + Bounds bounds = new Bounds(); + Enumeration> e = entities.elements(); + + while (e.hasMoreElements()) { + ArrayList list = e.nextElement(); + + Iterator i = list.iterator(); + + while (i.hasNext()) { + DXFEntity entity = (DXFEntity) i.next(); + Bounds b = entity.getBounds(); + + if (b.isValid()) { bounds.addToBounds(b); } + } + } + + return bounds; + } + + /** + * Get the bounds for the given filter flag. If true the bounds contains only entity bounds which are on model + * space. Else returns the bounds which contains the entity bounds which are on paperspace. + * + * @param onModelspace + * @return + */ + public Bounds getBounds(final boolean onModelspace) { + Bounds bounds = new Bounds(); + + Enumeration> e = entities.elements(); + + while (e.hasMoreElements()) { + ArrayList list = e.nextElement(); + + Iterator i = list.iterator(); + + while (i.hasNext()) { + DXFEntity entity = (DXFEntity) i.next(); + + if (onModelspace && entity.isModelSpace() || !onModelspace && !entity.isModelSpace()) { + Bounds b = entity.getBounds(); + + if (b.getMaximumX() == Double.NaN) { System.out.println("NANA=" + entity); } + + if (b.isValid()) { bounds.addToBounds(b); } + } + } + } + + return bounds; + } + + /** + * Returns the list of the DXFenetities of the Type or null. + * + * @param type + * @return List or null + */ + public List getDXFEntities(final String type) { + if (entities.containsKey(type)) return entities.get(type); + + return null; + } + + /** + * Checks for DXF entities. + * + * @param type + * the type + * @return true, if successful + */ + public boolean hasDXFEntities(final String type) { + return entities.containsKey(type); + } + + /** + * + * @return a iterator over all entity types of this layer + */ + public Iterator getDXFEntityTypeIterator() { return entities.keySet().iterator(); } + + /** + * Gets the + * + * @see DXFEntity with the specified ID. + * @param id + * of the + * @see DXFEntity + * @return the + * @see DXFEntity with the specified ID or null if there is no + * @see DXFEntity with the specified ID + */ + public DXFEntity getDXFEntityByID(final String id) { + DXFEntity entity = null; + Iterator> i = this.entities.values().iterator(); + + while (i.hasNext()) { + Iterator entityIterator = ((List) i.next()).iterator(); + + while (entityIterator.hasNext()) { + DXFEntity e = (DXFEntity) entityIterator.next(); + + if (e.getID().equals(id)) return e; + } + } + + return entity; + } + + /** + * Gets the color. + * + * @return the color + */ + public int getColor() { return this.color; } + + /** + * Sets the color. + * + * @param color + * the new color + */ + public void setColor(final int color) { this.color = color; } + + /** + * Sets the line type. + * + * @param ltype + * the new line type + */ + public void setLineType(final String ltype) { this.ltype = ltype; } + + /** + * Gets the line type. + * + * @return the line type + */ + public String getLineType() { return ltype; } + + /** + * @return Returns the flags. + */ + public int getFlags() { return flags; } + + /** + * @param flags + * The flags to set. + */ + public void setFlags(final int flags) { this.flags = flags; } + + /** + * Checks if is visible. + * + * @return true, if is visible + */ + public boolean isVisible() { return color >= 0; } + + /** + * Checks if is frozen. + * + * @return true, if is frozen + */ + public boolean isFrozen() { return (this.flags & 1) == 1; } + + /** + * Gets the line weight. + * + * @return the line weight + */ + public int getLineWeight() { return lineWeight; } + + /** + * Sets the line weight. + * + * @param lineWeight + * the new line weight + */ + public void setLineWeight(final int lineWeight) { this.lineWeight = lineWeight; } + + /** + * Gets the plot style. + * + * @return the plot style + */ + public String getPlotStyle() { return plotStyle; } + + /** + * Sets the plot style. + * + * @param plotStyle + * the new plot style + */ + public void setPlotStyle(final String plotStyle) { this.plotStyle = plotStyle; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLeader.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLeader.java index a2d8d0699c..8e0d1c49e7 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLeader.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFLeader.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFLeader.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -21,297 +16,293 @@ import msi.gama.ext.kabeja.dxf.helpers.Point; - /** * @author coordinates = new ArrayList<>(); + + /** The path type. */ + protected int pathType = 0; + + /** The creation type. */ + protected int creationType = 0; + + /** The hookline directon. */ + protected int hooklineDirecton = 0; + + /** The hookline. */ + protected boolean hookline = false; + + /** The horizontal direction. */ + protected Point horizontalDirection = new Point(); + + /** The last offset text. */ + protected Point lastOffsetText = new Point(); + + /** The last offset insertion. */ + protected Point lastOffsetInsertion = new Point(); + + /** The arrow enabled. */ + protected boolean arrowEnabled = false; + + /** The text ID. */ + protected String textID = ""; + + /** + * @return Returns the textID. + */ + public String getTextID() { return textID; } + + /** + * @param textID + * The textID to set. + */ + public void setTextID(final String textID) { this.textID = textID; } + + /* + * (non-Javadoc) + * + * @see org.kabeja.dxf.DXFEntity#getBounds() + */ + @Override + public Bounds getBounds() { + Bounds bounds = new Bounds(); + bounds.setValid(false); + + return bounds; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.dxf.DXFEntity#getType() + */ + @Override + public String getType() { return DXFConstants.ENTITY_TYPE_LEADER; } + + /** + * @return Returns the arrowHeadSize. + */ + public double getArrowHeadSize() { return arrowHeadSize; } + + /** + * @param arrowHeadSize + * The arrowHeadSize to set. + */ + public void setArrowHeadSize(final double arrowHeadSize) { this.arrowHeadSize = arrowHeadSize; } + + /** + * @return Returns the creationType. + */ + public int getCreationType() { return creationType; } + + /** + * @param creationType + * The creationType to set. + */ + public void setCreationType(final int creationType) { this.creationType = creationType; } + + /** + * @return Returns the hookline. + */ + public boolean isHookline() { return hookline; } + + /** + * @param hookline + * The hookline to set. + */ + public void setHookline(final boolean hookline) { this.hookline = hookline; } + + /** + * @return Returns the hooklineDirecton. + */ + public int getHooklineDirecton() { return hooklineDirecton; } + + /** + * @param hooklineDirecton + * The hooklineDirecton to set. + */ + public void setHooklineDirecton(final int hooklineDirecton) { this.hooklineDirecton = hooklineDirecton; } + + /** + * @return Returns the horizontalDirection. + */ + public Point getHorizontalDirection() { return horizontalDirection; } + + /** + * @param horizontalDirection + * The horizontalDirection to set. + */ + public void setHorizontalDirection(final Point horizontalDirection) { + this.horizontalDirection = horizontalDirection; + } + + /** + * @return Returns the lastOffsetInsertion. + */ + public Point getLastOffsetInsertion() { return lastOffsetInsertion; } + + /** + * @param lastOffsetInsertion + * The lastOffsetInsertion to set. + */ + public void setLastOffsetInsertion(final Point lastOffsetInsertion) { + this.lastOffsetInsertion = lastOffsetInsertion; + } + + /** + * @return Returns the lastOffsetText. + */ + public Point getLastOffsetText() { return lastOffsetText; } + + /** + * @param lastOffsetText + * The lastOffsetText to set. + */ + public void setLastOffsetText(final Point lastOffsetText) { this.lastOffsetText = lastOffsetText; } + + /** + * @return Returns the pathType. + */ + public int getPathType() { return pathType; } + + /** + * @param pathType + * The pathType to set. + */ + public void setPathType(final int pathType) { this.pathType = pathType; } + + /** + * @return Returns the scaleFactor. + */ + public double getScaleFactor() { return scaleFactor; } + + /** + * @param scaleFactor + * The scaleFactor to set. + */ + public void setScaleFactor(final double scaleFactor) { this.scaleFactor = scaleFactor; } + + /** + * @return Returns the styleName. + */ + public String getStyleNameID() { return styleName; } + + /** + * @param styleName + * The styleName to set. + */ + public void setStyleNameID(final String styleName) { this.styleName = styleName; } + + /** + * @return Returns the textGap. + */ + public double getTextGap() { return textGap; } + + /** + * @param textGap + * The textGap to set. + */ + public void setTextGap(final double textGap) { this.textGap = textGap; } + + /** + * @return Returns the textHeight. + */ + public double getTextHeight() { return textHeight; } + + /** + * @param textHeight + * The textHeight to set. + */ + public void setTextHeight(final double textHeight) { this.textHeight = textHeight; } + + /** + * @return Returns the textWidth. + */ + public double getTextWidth() { return textWidth; } + + /** + * @param textWidth + * The textWidth to set. + */ + public void setTextWidth(final double textWidth) { this.textWidth = textWidth; } + + /** + * Adds the coordinate. + * + * @param vertex the vertex + */ + public void addCoordinate(final Point vertex) { + coordinates.add(vertex); + } + + /** + * Gets the coordinate count. + * + * @return the coordinate count + */ + public int getCoordinateCount() { return this.coordinates.size(); } + + /** + * Gets the coordinate at. + * + * @param index the index + * @return the coordinate at + */ + public Point getCoordinateAt(final int index) { + return this.coordinates.get(index); + } + + /** + * Gets the coordinate iterator. + * + * @return the coordinate iterator + */ + public Iterator getCoordinateIterator() { return this.coordinates.iterator(); } + + /** + * @return Returns the arrowEnabled. + */ + public boolean isArrowEnabled() { return arrowEnabled; } + + /** + * @param arrowEnabled + * The arrowEnabled to set. + */ + public void setArrowEnabled(final boolean arrowEnabled) { this.arrowEnabled = arrowEnabled; } + + /** + * Checks if is spline path. + * + * @return true, if is spline path + */ + public boolean isSplinePath() { return this.pathType == 1; } + + @Override + public double getLength() { + // TODO Auto-generated method stub + return 0; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFMLine.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFMLine.java index cd1ea5c956..20de519106 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFMLine.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFMLine.java @@ -1,18 +1,12 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFMLine.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -22,126 +16,208 @@ import msi.gama.ext.kabeja.dxf.helpers.MLineConverter; import msi.gama.ext.kabeja.dxf.helpers.Point; - /** * @author polyline only after changes - DXFPolyline[] pl = toDXFPolylines(); - double l = 0; - - for (int i = 0; i < pl.length; i++) { - l += pl[i].getLength(); - } - - return l; - } - - public void addDXFMLineSegement(DXFMLineSegment seg) { - this.mlineSegments.add(seg); - } - - public int getDXFMLineSegmentCount() { - return this.mlineSegments.size(); - } - - public DXFMLineSegment getDXFMLineSegment(int index) { - return (DXFMLineSegment) this.mlineSegments.get(index); - } - - public double getScale() { - return scale; - } - - public void setScale(double scale) { - this.scale = scale; - } - - public Point getStartPoint() { - return startPoint; - } - - public void setStartPoint(Point startPoint) { - this.startPoint = startPoint; - } - - public int getLineCount() { - return lineCount; - } - - public void setLineCount(int lineCount) { - this.lineCount = lineCount; - } - - public String getMLineStyleID() { - return mLineStyleID; - } - - public void setMLineStyleID(String lineStyleID) { - mLineStyleID = lineStyleID; - } - - public int getJustification() { - return justification; - } - - public void setJustification(int justification) { - this.justification = justification; - } - - public String getMLineStyleName() { - return mLineStyleName; - } - - public void setMLineStyleName(String lineStyleName) { - mLineStyleName = lineStyleName; - } - - protected DXFPolyline[] toDXFPolylines() { - return MLineConverter.toDXFPolyline(this); - } - - public boolean isClosed() { - return (this.flags & 2) == 2; - } + + /** The Constant JUSTIFICATION_TOP. */ + public final static int JUSTIFICATION_TOP = 0; + + /** The Constant JUSTIFICATION_ZERO. */ + public final static int JUSTIFICATION_ZERO = 1; + + /** The Constant JUSTIFICATION_BOTTOM. */ + public final static int JUSTIFICATION_BOTTOM = 2; + + /** The scale. */ + protected double scale = 1.0; + + /** The start point. */ + protected Point startPoint = new Point(); + + /** The mline segments. */ + protected List mlineSegments = new ArrayList<>(); + + /** The line count. */ + protected int lineCount = 0; + + /** The justification. */ + protected int justification = 0; + + /** The m line style ID. */ + protected String mLineStyleID = ""; + + /** The m line style name. */ + protected String mLineStyleName = ""; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.dxf.DXFEntity#getBounds() + */ + @Override + public Bounds getBounds() { + Bounds b = new Bounds(); + DXFPolyline[] pl = this.toDXFPolylines(); + + for (DXFPolyline element : pl) { b.addToBounds(element.getBounds()); } + + // b.setValid(false); + return b; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.dxf.DXFEntity#getType() + */ + @Override + public String getType() { return DXFConstants.ENTITY_TYPE_MLINE; } + + @Override + public double getLength() { + // TODO convert mline -> polyline only after changes + DXFPolyline[] pl = toDXFPolylines(); + double l = 0; + + for (DXFPolyline element : pl) { l += element.getLength(); } + + return l; + } + + /** + * Adds the DXFM line segement. + * + * @param seg + * the seg + */ + public void addDXFMLineSegement(final DXFMLineSegment seg) { + this.mlineSegments.add(seg); + } + + /** + * Gets the DXFM line segment count. + * + * @return the DXFM line segment count + */ + public int getDXFMLineSegmentCount() { return this.mlineSegments.size(); } + + /** + * Gets the DXFM line segment. + * + * @param index + * the index + * @return the DXFM line segment + */ + public DXFMLineSegment getDXFMLineSegment(final int index) { + return this.mlineSegments.get(index); + } + + /** + * Gets the scale. + * + * @return the scale + */ + public double getScale() { return scale; } + + /** + * Sets the scale. + * + * @param scale + * the new scale + */ + public void setScale(final double scale) { this.scale = scale; } + + /** + * Gets the start point. + * + * @return the start point + */ + public Point getStartPoint() { return startPoint; } + + /** + * Sets the start point. + * + * @param startPoint + * the new start point + */ + public void setStartPoint(final Point startPoint) { this.startPoint = startPoint; } + + /** + * Gets the line count. + * + * @return the line count + */ + public int getLineCount() { return lineCount; } + + /** + * Sets the line count. + * + * @param lineCount + * the new line count + */ + public void setLineCount(final int lineCount) { this.lineCount = lineCount; } + + /** + * Gets the m line style ID. + * + * @return the m line style ID + */ + public String getMLineStyleID() { return mLineStyleID; } + + /** + * Sets the m line style ID. + * + * @param lineStyleID + * the new m line style ID + */ + public void setMLineStyleID(final String lineStyleID) { mLineStyleID = lineStyleID; } + + /** + * Gets the justification. + * + * @return the justification + */ + public int getJustification() { return justification; } + + /** + * Sets the justification. + * + * @param justification + * the new justification + */ + public void setJustification(final int justification) { this.justification = justification; } + + /** + * Gets the m line style name. + * + * @return the m line style name + */ + public String getMLineStyleName() { return mLineStyleName; } + + /** + * Sets the m line style name. + * + * @param lineStyleName + * the new m line style name + */ + public void setMLineStyleName(final String lineStyleName) { mLineStyleName = lineStyleName; } + + /** + * To DXF polylines. + * + * @return the DXF polyline[] + */ + protected DXFPolyline[] toDXFPolylines() { + return MLineConverter.toDXFPolyline(this); + } + + /** + * Checks if is closed. + * + * @return true, if is closed + */ + public boolean isClosed() { return (this.flags & 2) == 2; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFPolyline.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFPolyline.java index 4117b3347b..b722ccf383 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFPolyline.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFPolyline.java @@ -1,7 +1,12 @@ -/* - * Created on Jun 29, 2004 +/******************************************************************************************************* * - */ + * DXFPolyline.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.ArrayList; @@ -12,679 +17,728 @@ import msi.gama.ext.kabeja.dxf.helpers.Vector; import msi.gama.ext.kabeja.math.MathUtils; - /** * @author values = new Hashtable<>(); + + /** The name. */ + private String name = ""; + + /** + * Instantiates a new DXF variable. + * + * @param name + * the name + */ + public DXFVariable(final String name) { + this.name = name; + } - public String getName() { - return name; - } + /** + * Gets the name. + * + * @return the name + */ + public String getName() { return name; } - public void setName(String name) { - this.name = name; - } + /** + * Sets the name. + * + * @param name + * the new name + */ + public void setName(final String name) { this.name = name; } - public String getValue(String name) { - return (String) values.get(name); - } + /** + * Gets the value. + * + * @param name + * the name + * @return the value + */ + public String getValue(final String name) { + return values.get(name); + } - public int getIntegerValue(String name) { - return Integer.parseInt((String) values.get(name)); - } + /** + * Gets the integer value. + * + * @param name + * the name + * @return the integer value + */ + public int getIntegerValue(final String name) { + return Integer.parseInt(values.get(name)); + } - public double getDoubleValue(String name) { - return Double.parseDouble((String) values.get(name)); - } + /** + * Gets the double value. + * + * @param name + * the name + * @return the double value + */ + public double getDoubleValue(final String name) { + return Double.parseDouble(values.get(name)); + } - public void setValue(String name, String value) { - values.put(name, value); - } + /** + * Sets the value. + * + * @param name + * the name + * @param value + * the value + */ + public void setValue(final String name, final String value) { + values.put(name, value); + } - /** - * - * @return a iterator over all keys of this DXFValue - */ - public Iterator getValueKeyIterator() { - return values.keySet().iterator(); - } + /** + * + * @return a iterator over all keys of this DXFValue + */ + public Iterator getValueKeyIterator() { return values.keySet().iterator(); } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFViewport.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFViewport.java index 5e79cd9dfe..5550d162ef 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFViewport.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/DXFViewport.java @@ -1,18 +1,12 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFViewport.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf; import java.util.HashSet; @@ -24,529 +18,657 @@ import msi.gama.ext.kabeja.math.MathUtils; import msi.gama.ext.kabeja.math.ParametricPlane; - /** * @author 0) { - bounds.addToBounds(this.centerPoint.getX() - (this.width / 2), - this.centerPoint.getY() - (this.height / 2), 0.0); - bounds.addToBounds(this.centerPoint.getX() + (this.width / 2), - this.centerPoint.getY() + (this.height / 2), 0.0); - } - - return bounds; - } - - public double getLength() { - // TODO Auto-generated method stub - return 0; - } - - public String getType() { - return DXFConstants.ENTITY_TYPE_VIEWPORT; - } - - public double getWidth() { - return width; - } - - public void setWidth(double width) { - this.width = width; - } - - public void setRenderMode(int renderMode) { - this.renderMode = renderMode; - } - - public double getViewHeight() { - return viewHeight; - } - - public void setViewHeight(double viewHeight) { - this.viewHeight = viewHeight; - } - - public Vector getUcsOrigin() { - return ucsOrigin; - } - - public void setUcsOrigin(Vector ucsOrigin) { - this.ucsOrigin = ucsOrigin; - } - - public Vector getUcsXAxis() { - return ucsXAxis; - } - - public void setUcsXAxis(Vector ucsXAxis) { - this.ucsXAxis = ucsXAxis; - } - - public Vector getUcsYAxis() { - return ucsYAxis; - } - - public void setUcsYAxis(Vector ucsYAxis) { - this.ucsYAxis = ucsYAxis; - } - - public int getUcsType() { - return ucsType; - } - - public void setUcsType(int ucsType) { - this.ucsType = ucsType; - } - - public double getUcsElevation() { - return ucsElevation; - } - - public void setUcsElevation(double ucsElevation) { - this.ucsElevation = ucsElevation; - } - - public boolean isUseUCS() { - return useUCS; - } - - public void setUseUCS(boolean useUCS) { - this.useUCS = useUCS; - } - - public double getRatio() { - return ratio; - } - - public void setRatio(double ratio) { - this.ratio = ratio; - } - - public int getRenderMode() { - return renderMode; - } - - public double getSnapAngle() { - return snapAngle; - } - - public void setSnapAngle(double snapAngle) { - this.snapAngle = snapAngle; - } - - public Point getViewTargetPoint() { - return viewTargetPoint; - } - - public void setViewTargetPoint(Point viewTargetPoint) { - this.viewTargetPoint = viewTargetPoint; - } - - public Point getSnapSpacingPoint() { - return snapSpacingPoint; - } - - public void setSnapSpacingPoint(Point snapSpacingPoint) { - this.snapSpacingPoint = snapSpacingPoint; - } - - public String getPlotStyleName() { - return plotStyleName; - } - - public void setPlotStyleName(String plotStyleName) { - this.plotStyleName = plotStyleName; - } - - public int getViewportStatus() { - return viewportStatus; - } - - public void setViewportStatus(int viewportStatus) { - this.viewportStatus = viewportStatus; - } - - public double getTwistAngle() { - return twistAngle; - } - - public void addFrozenLayer(String layerName) { - this.frozenLayerSet.add(layerName); - } - - public boolean isFrozenLayer(String layerName) { - return this.frozenLayerSet.contains(layerName); - } - - public Iterator getFrozenLayerIterator() { - return this.frozenLayerSet.iterator(); - } - - public double getZoomXPFactor() { - if (this.viewHeight != 0.0) { - return this.height / this.viewHeight; - } else { - return this.calculateZoomXPFactor(); - } - } - - public double calculateZoomXPFactor() { - double c = (this.getViewDirectionVector().getLength() * 42) / this.lensLength; - double f = this.width / this.height; - double b = Math.sqrt((Math.pow(c, 2) / (Math.pow(f, 2) + 1))); - - return this.height / b; - } - - public Bounds getModelspaceViewBounds() { - double f = this.width / this.height; - - // the half of width and height - double modelH = (this.height / this.getZoomXPFactor()) / 2; - double modelW = (f * modelH); - double wf = modelW / modelH; - Vector directionX = null; - - if ((this.viewDirectionVector.getX() == 0.0) && - (this.viewDirectionVector.getY() == 0.0) && - (this.viewDirectionVector.getZ() == 1.0)) { - directionX = new Vector(1, 0, 0); - } else { - directionX = MathUtils.crossProduct(DXFConstants.DEFAULT_Z_AXIS_VECTOR, - this.viewDirectionVector); - } - - ParametricPlane plane = new ParametricPlane(this.viewTargetPoint, - directionX, - MathUtils.crossProduct(this.viewDirectionVector, directionX), - this.viewDirectionVector); - Bounds bounds = new Bounds(); - Point p = plane.getPoint(this.viewCenterPoint.getX() - modelW, - this.viewCenterPoint.getY() - modelH); - bounds.addToBounds(p); - p = plane.getPoint(this.viewCenterPoint.getX() + modelW, - this.viewCenterPoint.getY() + modelH); - bounds.addToBounds(p); - - return bounds; - } + + /** The viewport ID. */ + private String viewportID = ""; + + /** The plot style name. */ + private String plotStyleName = ""; + + /** The lower left corner. */ + private Point lowerLeftCorner = new Point(); + + /** The upper right corner. */ + private Point upperRightCorner = new Point(); + + /** The center point. */ + private Point centerPoint = new Point(); + + /** The snap base point. */ + private Point snapBasePoint = new Point(); + + /** The snap spacing point. */ + private Point snapSpacingPoint = new Point(); + + /** The grid spacing point. */ + private Point gridSpacingPoint = new Point(); + + /** The view direction vector. */ + private Vector viewDirectionVector = new Vector(); + + /** The view center point. */ + private Point viewCenterPoint = new Point(); + + /** The view target point. */ + private Point viewTargetPoint = new Point(); + + /** The ucs origin. */ + private Vector ucsOrigin = new Vector(); + + /** The ucs X axis. */ + private Vector ucsXAxis = new Vector(); + + /** The ucs Y axis. */ + private Vector ucsYAxis = new Vector(); + + /** The ucs type. */ + private int ucsType = 0; + + /** The viewport status. */ + private int viewportStatus = 0; + + /** The ucs elevation. */ + private double ucsElevation = 0.0; + + /** The use UCS. */ + private boolean useUCS = false; + + /** The height. */ + private double height; + + /** The width. */ + private double width; + + /** The ratio. */ + private double ratio; + + /** The lens length. */ + private double lensLength; + + /** The view height. */ + private double viewHeight; + + /** The front clipping plane. */ + private double frontClippingPlane; + + /** The back clipping plane. */ + private double backClippingPlane; + + /** The twist angle. */ + private double twistAngle; + + /** The snap angle. */ + private double snapAngle; + + /** The circle zoom. */ + private double circleZoom; + + /** The fast zoom. */ + private double fastZoom; + + /** The snap. */ + private boolean snap; + + /** The grid. */ + private boolean grid; + + /** The active. */ + private boolean active = false; + + /** The render mode. */ + private int renderMode; + + /** The frozen layer set. */ + private final Set frozenLayerSet = new HashSet<>(); + + /** + * @return Returns the backClippingPlane. + */ + public double getBackClippingPlane() { return backClippingPlane; } + + /** + * @param backClippingPlane + * The backClippingPlane to set. + */ + public void setBackClippingPlane(final double backClippingPlane) { this.backClippingPlane = backClippingPlane; } + + /** + * @return Returns the centerPoint. + */ + public Point getCenterPoint() { return centerPoint; } + + /** + * @param centerPoint + * The centerPoint to set. + */ + public void setCenterPoint(final Point centerPoint) { this.centerPoint = centerPoint; } + + /** + * @return Returns the circleZoom. + */ + public double getCircleZoom() { return circleZoom; } + + /** + * @param circleZoom + * The circleZoom to set. + */ + public void setCircleZoom(final double circleZoom) { this.circleZoom = circleZoom; } + + /** + * @return Returns the fastZoom. + */ + public double getFastZoom() { return fastZoom; } + + /** + * @param fastZoom + * The fastZoom to set. + */ + public void setFastZoom(final double fastZoom) { this.fastZoom = fastZoom; } + + /** + * @return Returns the frontClippingPlane. + */ + public double getFrontClippingPlane() { return frontClippingPlane; } + + /** + * @param frontClippingPlane + * The frontClippingPlane to set. + */ + public void setFrontClippingPlane(final double frontClippingPlane) { + this.frontClippingPlane = frontClippingPlane; + } + + /** + * @return Returns the grid. + */ + public boolean isGrid() { return grid; } + + /** + * @param grid + * The grid to set. + */ + public void setGrid(final boolean grid) { this.grid = grid; } + + /** + * @return Returns the gridSpacingPoint. + */ + public Point getGridSpacingPoint() { return gridSpacingPoint; } + + /** + * @param gridSpacingPoint + * The gridSpacingPoint to set. + */ + public void setGridSpacingPoint(final Point gridSpacingPoint) { this.gridSpacingPoint = gridSpacingPoint; } + + /** + * @return Returns the height. + */ + public double getHeight() { return height; } + + /** + * @param height + * The height to set. + */ + public void setHeight(final double height) { this.height = height; } + + /** + * @return Returns the lensLength. + */ + public double getLensLength() { return lensLength; } + + /** + * @param lensLength + * The lensLength to set. + */ + public void setLensLength(final double lensLength) { this.lensLength = lensLength; } + + /** + * @return Returns the lowerLeftCorner. + */ + public Point getLowerLeftCorner() { return lowerLeftCorner; } + + /** + * @param lowerLeftCorner + * The lowerLeftCorner to set. + */ + public void setLowerLeftCorner(final Point lowerLeftCorner) { this.lowerLeftCorner = lowerLeftCorner; } + + /** + * @return Returns the name. + */ + public String getViewportID() { return viewportID; } + + /** + * @param name + * The name to set. + */ + public void setViewportID(final String name) { this.viewportID = name; } + + /** + * @return Returns the ratio. + */ + public double getAspectRatio() { return ratio; } + + /** + * @param ratio + * The ratio to set. + */ + public void setAspectRatio(final double ratio) { this.ratio = ratio; } + + /** + * @param rotationAngle + * The rotationAngle to set. + */ + public void setTwistAngle(final double rotationAngle) { this.twistAngle = rotationAngle; } + + /** + * @return Returns the snap. + */ + public boolean isSnap() { return snap; } + + /** + * @param snap + * The snap to set. + */ + public void setSnap(final boolean snap) { this.snap = snap; } + + /** + * @return Returns the snapBasePoint. + */ + public Point getSnapBasePoint() { return snapBasePoint; } + + /** + * @param snapBasePoint + * The snapBasePoint to set. + */ + public void setSnapBasePoint(final Point snapBasePoint) { this.snapBasePoint = snapBasePoint; } + + /** + * @return Returns the upperRightCorner. + */ + public Point getUpperRightCorner() { return upperRightCorner; } + + /** + * @param upperRightCorner + * The upperRightCorner to set. + */ + public void setUpperRightCorner(final Point upperRightCorner) { this.upperRightCorner = upperRightCorner; } + + /** + * @return Returns the viewDirectionPoint. + */ + public Vector getViewDirectionVector() { return viewDirectionVector; } + + /** + * @param viewDirectionPoint + * The viewDirectionPoint to set. + */ + public void setViewDirectionVector(final Vector viewDirectionPoint) { + this.viewDirectionVector = viewDirectionPoint; + } + + /** + * @return Returns the viewTargetPoint. + */ + public Point getViewCenterPoint() { return viewCenterPoint; } + + /** + * @param viewTargetPoint + * The viewTargetPoint to set. + */ + public void setViewCenterPoint(final Point viewTargetPoint) { this.viewCenterPoint = viewTargetPoint; } + + /** + * @return Returns the active. + */ + public boolean isActive() { return active; } + + /** + * @param active + * The active to set. + */ + public void setActive(final boolean active) { this.active = active; } + + @Override + public Bounds getBounds() { + Bounds bounds = new Bounds(); + + if (this.viewportStatus > 0) { + bounds.addToBounds(this.centerPoint.getX() - this.width / 2, this.centerPoint.getY() - this.height / 2, + 0.0); + bounds.addToBounds(this.centerPoint.getX() + this.width / 2, this.centerPoint.getY() + this.height / 2, + 0.0); + } + + return bounds; + } + + @Override + public double getLength() { + // TODO Auto-generated method stub + return 0; + } + + @Override + public String getType() { return DXFConstants.ENTITY_TYPE_VIEWPORT; } + + /** + * Gets the width. + * + * @return the width + */ + public double getWidth() { return width; } + + /** + * Sets the width. + * + * @param width + * the new width + */ + public void setWidth(final double width) { this.width = width; } + + /** + * Sets the render mode. + * + * @param renderMode + * the new render mode + */ + public void setRenderMode(final int renderMode) { this.renderMode = renderMode; } + + /** + * Gets the view height. + * + * @return the view height + */ + public double getViewHeight() { return viewHeight; } + + /** + * Sets the view height. + * + * @param viewHeight + * the new view height + */ + public void setViewHeight(final double viewHeight) { this.viewHeight = viewHeight; } + + /** + * Gets the ucs origin. + * + * @return the ucs origin + */ + public Vector getUcsOrigin() { return ucsOrigin; } + + /** + * Sets the ucs origin. + * + * @param ucsOrigin + * the new ucs origin + */ + public void setUcsOrigin(final Vector ucsOrigin) { this.ucsOrigin = ucsOrigin; } + + /** + * Gets the ucs X axis. + * + * @return the ucs X axis + */ + public Vector getUcsXAxis() { return ucsXAxis; } + + /** + * Sets the ucs X axis. + * + * @param ucsXAxis + * the new ucs X axis + */ + public void setUcsXAxis(final Vector ucsXAxis) { this.ucsXAxis = ucsXAxis; } + + /** + * Gets the ucs Y axis. + * + * @return the ucs Y axis + */ + public Vector getUcsYAxis() { return ucsYAxis; } + + /** + * Sets the ucs Y axis. + * + * @param ucsYAxis + * the new ucs Y axis + */ + public void setUcsYAxis(final Vector ucsYAxis) { this.ucsYAxis = ucsYAxis; } + + /** + * Gets the ucs type. + * + * @return the ucs type + */ + public int getUcsType() { return ucsType; } + + /** + * Sets the ucs type. + * + * @param ucsType + * the new ucs type + */ + public void setUcsType(final int ucsType) { this.ucsType = ucsType; } + + /** + * Gets the ucs elevation. + * + * @return the ucs elevation + */ + public double getUcsElevation() { return ucsElevation; } + + /** + * Sets the ucs elevation. + * + * @param ucsElevation + * the new ucs elevation + */ + public void setUcsElevation(final double ucsElevation) { this.ucsElevation = ucsElevation; } + + /** + * Checks if is use UCS. + * + * @return true, if is use UCS + */ + public boolean isUseUCS() { return useUCS; } + + /** + * Sets the use UCS. + * + * @param useUCS + * the new use UCS + */ + public void setUseUCS(final boolean useUCS) { this.useUCS = useUCS; } + + /** + * Gets the ratio. + * + * @return the ratio + */ + public double getRatio() { return ratio; } + + /** + * Sets the ratio. + * + * @param ratio + * the new ratio + */ + public void setRatio(final double ratio) { this.ratio = ratio; } + + /** + * Gets the render mode. + * + * @return the render mode + */ + public int getRenderMode() { return renderMode; } + + /** + * Gets the snap angle. + * + * @return the snap angle + */ + public double getSnapAngle() { return snapAngle; } + + /** + * Sets the snap angle. + * + * @param snapAngle + * the new snap angle + */ + public void setSnapAngle(final double snapAngle) { this.snapAngle = snapAngle; } + + /** + * Gets the view target point. + * + * @return the view target point + */ + public Point getViewTargetPoint() { return viewTargetPoint; } + + /** + * Sets the view target point. + * + * @param viewTargetPoint + * the new view target point + */ + public void setViewTargetPoint(final Point viewTargetPoint) { this.viewTargetPoint = viewTargetPoint; } + + /** + * Gets the snap spacing point. + * + * @return the snap spacing point + */ + public Point getSnapSpacingPoint() { return snapSpacingPoint; } + + /** + * Sets the snap spacing point. + * + * @param snapSpacingPoint + * the new snap spacing point + */ + public void setSnapSpacingPoint(final Point snapSpacingPoint) { this.snapSpacingPoint = snapSpacingPoint; } + + /** + * Gets the plot style name. + * + * @return the plot style name + */ + public String getPlotStyleName() { return plotStyleName; } + + /** + * Sets the plot style name. + * + * @param plotStyleName + * the new plot style name + */ + public void setPlotStyleName(final String plotStyleName) { this.plotStyleName = plotStyleName; } + + /** + * Gets the viewport status. + * + * @return the viewport status + */ + public int getViewportStatus() { return viewportStatus; } + + /** + * Sets the viewport status. + * + * @param viewportStatus + * the new viewport status + */ + public void setViewportStatus(final int viewportStatus) { this.viewportStatus = viewportStatus; } + + /** + * Gets the twist angle. + * + * @return the twist angle + */ + public double getTwistAngle() { return twistAngle; } + + /** + * Adds the frozen layer. + * + * @param layerName + * the layer name + */ + public void addFrozenLayer(final String layerName) { + this.frozenLayerSet.add(layerName); + } + + /** + * Checks if is frozen layer. + * + * @param layerName + * the layer name + * @return true, if is frozen layer + */ + public boolean isFrozenLayer(final String layerName) { + return this.frozenLayerSet.contains(layerName); + } + + /** + * Gets the frozen layer iterator. + * + * @return the frozen layer iterator + */ + public Iterator getFrozenLayerIterator() { return this.frozenLayerSet.iterator(); } + + /** + * Gets the zoom XP factor. + * + * @return the zoom XP factor + */ + public double getZoomXPFactor() { + if (this.viewHeight != 0.0) return this.height / this.viewHeight; + return this.calculateZoomXPFactor(); + } + + /** + * Calculate zoom XP factor. + * + * @return the double + */ + public double calculateZoomXPFactor() { + double c = this.getViewDirectionVector().getLength() * 42 / this.lensLength; + double f = this.width / this.height; + double b = Math.sqrt(Math.pow(c, 2) / (Math.pow(f, 2) + 1)); + + return this.height / b; + } + + /** + * Gets the modelspace view bounds. + * + * @return the modelspace view bounds + */ + public Bounds getModelspaceViewBounds() { + double f = this.width / this.height; + + // the half of width and height + double modelH = this.height / this.getZoomXPFactor() / 2; + double modelW = f * modelH; + // double wf = modelW / modelH; + Vector directionX = null; + + if (this.viewDirectionVector.getX() == 0.0 && this.viewDirectionVector.getY() == 0.0 + && this.viewDirectionVector.getZ() == 1.0) { + directionX = new Vector(1, 0, 0); + } else { + directionX = MathUtils.crossProduct(DXFConstants.DEFAULT_Z_AXIS_VECTOR, this.viewDirectionVector); + } + + ParametricPlane plane = new ParametricPlane(this.viewTargetPoint, directionX, + MathUtils.crossProduct(this.viewDirectionVector, directionX), this.viewDirectionVector); + Bounds bounds = new Bounds(); + Point p = plane.getPoint(this.viewCenterPoint.getX() - modelW, this.viewCenterPoint.getY() - modelH); + bounds.addToBounds(p); + p = plane.getPoint(this.viewCenterPoint.getX() + modelW, this.viewCenterPoint.getY() + modelH); + bounds.addToBounds(p); + + return bounds; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFMLineSegment.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFMLineSegment.java index c1b346b1fa..1495ba0f1b 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFMLineSegment.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFMLineSegment.java @@ -1,63 +1,100 @@ -/* - Copyright 2008 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFMLineSegment.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf.helpers; import java.util.ArrayList; import java.util.List; - +/** + * The Class DXFMLineSegment. + */ public class DXFMLineSegment { - protected Point startPoint = new Point(); - protected Vector direction = new Vector(); - protected Vector miterDirection = new Vector(); - protected List elements = new ArrayList(); - - public Point getStartPoint() { - return startPoint; - } - - public void setStartPoint(Point startPoint) { - this.startPoint = startPoint; - } - - public Vector getDirection() { - return direction; - } - - public void setDirection(Vector direction) { - this.direction = direction; - } - - public Vector getMiterDirection() { - return miterDirection; - } - - public void setMiterDirection(Vector miterDirection) { - this.miterDirection = miterDirection; - } - - public void addDXFMLineSegmentElement(DXFMLineSegmentElement el) { - this.elements.add(el); - } - - public int getDXFMLineSegmentElementCount() { - return this.elements.size(); - } - - public DXFMLineSegmentElement getDXFMLineSegmentElement(int index) { - return (DXFMLineSegmentElement) this.elements.get(index); - } + + /** The start point. */ + protected Point startPoint = new Point(); + + /** The direction. */ + protected Vector direction = new Vector(); + + /** The miter direction. */ + protected Vector miterDirection = new Vector(); + + /** The elements. */ + protected List elements = new ArrayList<>(); + + /** + * Gets the start point. + * + * @return the start point + */ + public Point getStartPoint() { return startPoint; } + + /** + * Sets the start point. + * + * @param startPoint the new start point + */ + public void setStartPoint(final Point startPoint) { this.startPoint = startPoint; } + + /** + * Gets the direction. + * + * @return the direction + */ + public Vector getDirection() { return direction; } + + /** + * Sets the direction. + * + * @param direction the new direction + */ + public void setDirection(final Vector direction) { this.direction = direction; } + + /** + * Gets the miter direction. + * + * @return the miter direction + */ + public Vector getMiterDirection() { return miterDirection; } + + /** + * Sets the miter direction. + * + * @param miterDirection the new miter direction + */ + public void setMiterDirection(final Vector miterDirection) { this.miterDirection = miterDirection; } + + /** + * Adds the DXFM line segment element. + * + * @param el the el + */ + public void addDXFMLineSegmentElement(final DXFMLineSegmentElement el) { + this.elements.add(el); + } + + /** + * Gets the DXFM line segment element count. + * + * @return the DXFM line segment element count + */ + public int getDXFMLineSegmentElementCount() { return this.elements.size(); } + + /** + * Gets the DXFM line segment element. + * + * @param index the index + * @return the DXFM line segment element + */ + public DXFMLineSegmentElement getDXFMLineSegmentElement(final int index) { + return this.elements.get(index); + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFSplineConverter.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFSplineConverter.java index 8ac4c5fe0a..514371d807 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFSplineConverter.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFSplineConverter.java @@ -1,18 +1,13 @@ -/* - Copyright 2008 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFSplineConverter.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf.helpers; import java.util.ArrayList; @@ -24,54 +19,61 @@ import msi.gama.ext.kabeja.math.NURBS; import msi.gama.ext.kabeja.math.NURBSFixedNTELSPointIterator; - +/** + * The Class DXFSplineConverter. + */ public class DXFSplineConverter { - public static DXFPolyline toDXFPolyline(DXFSpline spline) { - DXFPolyline p = new DXFPolyline(); - p.setDXFDocument(spline.getDXFDocument()); - - if ((spline.getDegree() > 0) && (spline.getKnots().length > 0)) { - Iterator pi = new NURBSFixedNTELSPointIterator(toNurbs(spline), 30); - - while (pi.hasNext()) { - p.addVertex(new DXFVertex((Point) pi.next())); - } - } else { - // the curve is the controlpoint polygon - Iterator i = spline.getSplinePointIterator(); - - while (i.hasNext()) { - SplinePoint sp = (SplinePoint) i.next(); - - if (sp.isControlPoint()) { - p.addVertex(new DXFVertex(sp)); - } - } - } - - if (spline.isClosed()) { - p.setFlags(1); - } - - return p; - } - - public static NURBS toNurbs(DXFSpline spline) { - Iterator i = spline.getSplinePointIterator(); - ArrayList list = new ArrayList(); - - while (i.hasNext()) { - SplinePoint sp = (SplinePoint) i.next(); - - if (sp.isControlPoint()) { - list.add(sp); - } - } - - NURBS n = new NURBS((Point[]) list.toArray(new Point[list.size()]), - spline.getKnots(), spline.getWeights(), spline.getDegree()); - n.setClosed(spline.isClosed()); - - return n; - } + + /** + * To DXF polyline. + * + * @param spline the spline + * @return the DXF polyline + */ + public static DXFPolyline toDXFPolyline(final DXFSpline spline) { + DXFPolyline p = new DXFPolyline(); + p.setDXFDocument(spline.getDXFDocument()); + + if (spline.getDegree() > 0 && spline.getKnots().length > 0) { + Iterator pi = new NURBSFixedNTELSPointIterator(toNurbs(spline), 30); + + while (pi.hasNext()) { p.addVertex(new DXFVertex((Point) pi.next())); } + } else { + // the curve is the controlpoint polygon + Iterator i = spline.getSplinePointIterator(); + + while (i.hasNext()) { + SplinePoint sp = (SplinePoint) i.next(); + + if (sp.isControlPoint()) { p.addVertex(new DXFVertex(sp)); } + } + } + + if (spline.isClosed()) { p.setFlags(1); } + + return p; + } + + /** + * To nurbs. + * + * @param spline the spline + * @return the nurbs + */ + public static NURBS toNurbs(final DXFSpline spline) { + Iterator i = spline.getSplinePointIterator(); + ArrayList list = new ArrayList<>(); + + while (i.hasNext()) { + SplinePoint sp = (SplinePoint) i.next(); + + if (sp.isControlPoint()) { list.add(sp); } + } + + NURBS n = new NURBS(list.toArray(new Point[list.size()]), spline.getKnots(), spline.getWeights(), + spline.getDegree()); + n.setClosed(spline.isClosed()); + + return n; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFTextParser.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFTextParser.java index 4b756efe25..1764fd1d59 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFTextParser.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFTextParser.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFTextParser.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf.helpers; import java.util.Stack; @@ -21,642 +16,652 @@ import msi.gama.ext.kabeja.dxf.DXFMText; import msi.gama.ext.kabeja.dxf.DXFText; - /** * @author (i + 6)) && (text.charAt(i + 1) == 'U') && - (text.charAt(i + 2) == '+')) { - String part = text.substring(i + 3, i + 7); - int unicode = Integer.parseInt(part, 16); - buf.append((char) unicode); - i += 6; - } else { - buf.append('\\'); - } - } else { - if (marker == 0) { - buf.append(c); - } else if (marker == 1) { - // the control % self - buf.append('%'); - marker = 0; - } else if (marker == 2) { - switch (c) { - case 'd': - buf.append('\u00B0'); - - break; - - case 'c': - buf.append('\u2205'); - - break; - - case 'p': - buf.append('\u00B1'); - - break; - - default: - - if (Character.isDigit(c) && ((i + 2) < text.length())) { - String code = "" + c + text.charAt(i + 1) + - text.charAt(i + 2); - - try { - c = (char) Integer.parseInt(code); - buf.append(c); - i += 2; - } catch (NumberFormatException e) { - // TODO sometimes there is only one - // digit, so what should be the - //replacement??? - buf.append('?'); - i++; - } - } else { - //a style control write back - buf.append("%%"); - buf.append(c); - } - } - - marker = 0; - } else if (marker == 3) { - buf.append('%'); - marker = 0; - } - } - } - - if ((marker == 1) || (marker == 3)) { - buf.append('%'); - } - - return buf.toString(); - } + if (value.endsWith("x")) { + para.setFontHeight( + para.getFontHeight() * Double.parseDouble(value.substring(0, value.length() - 1))); + } else { + para.setFontHeight(Double.parseDouble(value)); + } + + break; + + case 'Q': + para.setObliquiAngle(Double.parseDouble(value)); + + break; + + case 'W': + para.setWidth(Double.parseDouble(value)); + + break; + + case 'T': + para.setCharacterspace(Double.parseDouble(value)); + + break; + + case 'f': + parseFontSettings(value.trim(), para); + + break; + + case 'F': + para.setFontFile(value.trim()); + + break; + + case 'S': + + // TODO handle + break; + } + } + + /** + * Parses the font settings. + * + * @param value the value + * @param para the para + */ + public static void parseFontSettings(final String value, final StyledTextParagraph para) { + StringTokenizer st = new StringTokenizer(value, "|"); + para.setFont(st.nextToken()); + + while (st.hasMoreTokens()) { + String option = st.nextToken(); + char code = option.charAt(0); + int i = Integer.parseInt(option.substring(1)); + + switch (code) { + case 'b': + para.setBold(i == 1); + + break; + + case 'i': + para.setItalic(i == 1); + + break; + + case 'c': + + // ??? color? + break; + + case 'p': + + // ??? + break; + } + } + } + + /** + * Parses the symbols. + * + * @param text the text + * @return the string + */ + public static String parseSymbols(final String text) { + boolean asciicontrol = false; + StringBuilder buf = new StringBuilder(); + int marker = 0; + char c; + + for (int i = 0; i < text.length(); i++) { + c = text.charAt(i); + + if (c == '%') { + if (marker == 2) { + // a sequence of %%%%%065 means '%A' + buf.append('%'); + marker = 0; + } else { + marker++; + } + } else if (c == '^') { + asciicontrol = true; + } else if (asciicontrol) { + // ASCII-control sign map + if (Character.isWhitespace(c)) { + buf.append('^'); + } else { + // filtering acsii controls here + } + + asciicontrol = false; + } else if (c == '\\') { + // test for unicode + if (text.length() > i + 6 && text.charAt(i + 1) == 'U' && text.charAt(i + 2) == '+') { + String part = text.substring(i + 3, i + 7); + int unicode = Integer.parseInt(part, 16); + buf.append((char) unicode); + i += 6; + } else { + buf.append('\\'); + } + } else { + switch (marker) { + case 0: + buf.append(c); + break; + case 1: + // the control % self + buf.append('%'); + marker = 0; + break; + case 2: + switch (c) { + case 'd': + buf.append('\u00B0'); + + break; + + case 'c': + buf.append('\u2205'); + + break; + + case 'p': + buf.append('\u00B1'); + + break; + + default: + + if (Character.isDigit(c) && i + 2 < text.length()) { + String code = "" + c + text.charAt(i + 1) + text.charAt(i + 2); + + try { + c = (char) Integer.parseInt(code); + buf.append(c); + i += 2; + } catch (NumberFormatException e) { + // TODO sometimes there is only one + // digit, so what should be the + // replacement??? + buf.append('?'); + i++; + } + } else { + // a style control write back + buf.append("%%"); + buf.append(c); + } + } + marker = 0; + break; + case 3: + buf.append('%'); + marker = 0; + break; + default: + break; + } + } + } + + if (marker == 1 || marker == 3) { buf.append('%'); } + + return buf.toString(); + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFUtils.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFUtils.java index c38343d773..771b4f6392 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFUtils.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/DXFUtils.java @@ -1,18 +1,12 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFUtils.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf.helpers; import java.util.ArrayList; @@ -22,128 +16,175 @@ import msi.gama.ext.kabeja.dxf.DXFVertex; import msi.gama.ext.kabeja.math.MathUtils; - /** * @author startLength) { - this.currentLength = l - startLength; - - if (pattern[i] < 0) { - //System.out.println("is empty"); - this.currentLength *= (-1); - } - - //System.out.println("pattern startet bei="+i+" mit length="+this.currentLength); - this.index = i + 1; - - return; - } - } - } - - public boolean isSolid() { - return pattern.length == 0; - } + + /** The start point. */ + protected Point startPoint; + + /** The direction. */ + protected Vector direction; + + /** The angle. */ + protected double angle; + + /** The total length. */ + protected double totalLength; + + /** The length. */ + protected double length; + + /** The current length. */ + protected double currentLength; + + /** The pattern. */ + protected double[] pattern; + + /** The l. */ + protected double l; + + /** The index. */ + protected int index; + + /** The line. */ + protected ParametricLine line; + + /** + * + * @param startPoint + * @param angle + * the angle in degrees + */ + public HatchLineSegment(final Point startPoint, final double angle, final double length) { + this.startPoint = startPoint; + this.angle = Math.toRadians(angle); + this.totalLength = length; + } + + /** + * Instantiates a new hatch line segment. + * + * @param startPoint the start point + * @param direction the direction + * @param length the length + */ + public HatchLineSegment(final Point startPoint, final Vector direction, final double length) { + this.startPoint = startPoint; + this.direction = direction; + this.totalLength = length; + } + + /** + * Instantiates a new hatch line segment. + * + * @param line the line + * @param length the length + * @param startLength the start length + * @param pattern the pattern + */ + public HatchLineSegment(final ParametricLine line, final double length, final double startLength, + final double[] pattern) { + this.startPoint = line.getStartPoint(); + // this.angle = Math.toRadians(angle); + this.totalLength = length; + this.currentLength = startLength; + this.pattern = pattern; + this.line = line; + this.initialize(startLength); + } + + /** + * Gets the start point. + * + * @return the start point + */ + public Point getStartPoint() { return this.startPoint; } + + /** + * Gets the length. + * + * @return the length + */ + public double getLength() { return this.totalLength; } + + /** + * Gets the point. + * + * @param offset the offset + * @return the point + */ + public Point getPoint(final double offset) { + Point p = new Point(); + p.setX(this.startPoint.getX() + Math.cos(this.angle) * this.totalLength); + p.setY(this.startPoint.getY() + Math.sin(this.angle) * this.totalLength); + + return p; + } + + /** + * Gets the point at. + * + * @param para the para + * @return the point at + */ + public Point getPointAt(final double para) { + return line.getPointAt(para); + } + + /** + * Checks for next. + * + * @return true, if successful + */ + public boolean hasNext() { + return this.length <= totalLength; + } + + /** + * Next. + * + * @return the double + */ + public double next() { + double l = this.currentLength; + this.length += Math.abs(this.currentLength); + + if (index == pattern.length) { index = 0; } + + this.currentLength = pattern[index]; + index++; + + return l; + } + + /** + * Initialize. + * + * @param startLength the start length + */ + protected void initialize(final double startLength) { + double l = 0; + + for (int i = 0; i < pattern.length; i++) { + l += Math.abs(pattern[i]); + + // System.out.println("test Pattern part:"+pattern[i]+" startLength="+startLength+" currentLength:"+l); + if (l > startLength) { + this.currentLength = l - startLength; + + if (pattern[i] < 0) { + // System.out.println("is empty"); + this.currentLength *= -1; + } + + // System.out.println("pattern startet bei="+i+" mit length="+this.currentLength); + this.index = i + 1; + + return; + } + } + } + + /** + * Checks if is solid. + * + * @return true, if is solid + */ + public boolean isSolid() { return pattern.length == 0; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/Point.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/Point.java index e384955cad..c4e7a4b391 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/Point.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/helpers/Point.java @@ -1,22 +1,18 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * Point.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf.helpers; -import msi.gama.ext.kabeja.dxf.DXFConstants; +import java.util.Objects; +import msi.gama.ext.kabeja.dxf.DXFConstants; /** * @author records = new ArrayList<>(); + + @Override + public String getObjectType() { return DXFConstants.OBJECT_TYPE_DICTIONARY; } + + /** + * Checks for DXF object by ID. + * + * @param id the id + * @return true, if successful + */ + public boolean hasDXFObjectByID(final String id) { + return findByID(id) != null; + } + + /** + * Gets the name for DXF object ID. + * + * @param id the id + * @return the name for DXF object ID + */ + public String getNameForDXFObjectID(final String id) { + return findByID(id).getName(); + } + + /** + * Gets the + * + * @see DXFObject with the specified ID. + * @param id + * @return the DXFObject or null if there is no such DXFObject + */ + public DXFObject getDXFObjectByID(final String id) { + // search for child dictionaries + DXFDictionary dic = this.getDXFDictionaryForID(id); + + if (dic != null) { + DXFDictionaryRecord dicRecord = dic.findByID(id); + + if (dicRecord != null) return dicRecord.getDXFObject(); + } + + return null; + } + + /** + * Gets the DXF object by name. + * + * @param name the name + * @return the DXF object by name + */ + public DXFObject getDXFObjectByName(final String name) { + DXFDictionaryRecord record = findByName(name); + + if (record != null) return record.getDXFObject(); + + return null; + } + + /** + * Put DXF object. + * + * @param obj the obj + */ + public void putDXFObject(final DXFObject obj) { + findByID(obj.getID()).setDXFObject(obj); + } + + /** + * Put DXF object relation. + * + * @param name the name + * @param id the id + */ + public void putDXFObjectRelation(final String name, final String id) { + DXFDictionaryRecord record = null; + + if ((record = findByName(name)) != null) { + record.setID(id); + } else { + record = new DXFDictionaryRecord(name, id); + this.records.add(record); + } + } + + /** + * Find by name. + * + * @param name the name + * @return the DXF dictionary record + */ + protected DXFDictionaryRecord findByName(final String name) { + for (int i = 0; i < this.records.size(); i++) { + DXFDictionaryRecord record = records.get(i); + + if (record.getName().equals(name)) return record; + } + + return null; + } + + /** + * Find by ID. + * + * @param id the id + * @return the DXF dictionary record + */ + protected DXFDictionaryRecord findByID(final String id) { + for (int i = 0; i < this.records.size(); i++) { + DXFDictionaryRecord record = records.get(i); + + if (record.getID().equals(id)) return record; + } + + return null; + } + + /** + * Searches recursive for the dictionary which holds the ID + * + * @param id + * @return the dictionary or null + */ + public DXFDictionary getDXFDictionaryForID(final String id) { + Set dictionaries = new HashSet<>(); + DXFObject obj = null; + + for (int i = 0; i < this.records.size(); i++) { + DXFDictionaryRecord record = records.get(i); + + if (record.getID().equals(id)) return this; + if ((obj = record.getDXFObject()) != null + && DXFConstants.OBJECT_TYPE_DICTIONARY.equals(obj.getObjectType())) { + dictionaries.add(obj); + } + } + + Iterator ie = dictionaries.iterator(); + + while (ie.hasNext()) { + DXFDictionary dic = (DXFDictionary) ie.next(); + DXFDictionary d = dic.getDXFDictionaryForID(id); + + if (d != null) return d; + } + + return null; + } + + /** + * + * @return iterator over all DXFObjects in this dictionary + */ + public Iterator getDXFObjectIterator() { + return new Iterator() { + int count = 0; + + @Override + public boolean hasNext() { + return count < records.size(); + } + + @Override + public Object next() { + return records.get(count++).getDXFObject(); + } + + @Override + public void remove() { + records.remove(count - 1); + } + }; + } + + /** + * The Class DXFDictionaryRecord. + */ + private static class DXFDictionaryRecord { + + /** The id. */ + private String id; + + /** The name. */ + private final String name; + + /** The obj. */ + private DXFObject obj; + + /** + * Instantiates a new DXF dictionary record. + * + * @param name the name + * @param id the id + */ + public DXFDictionaryRecord(final String name, final String id) { + this.id = id; + this.name = name; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { return this.name; } + + /** + * Gets the id. + * + * @return the id + */ + public String getID() { return this.id; } + + /** + * Sets the id. + * + * @param id the new id + */ + public void setID(final String id) { this.id = id; } + + /** + * Sets the DXF object. + * + * @param obj the new DXF object + */ + public void setDXFObject(final DXFObject obj) { this.obj = obj; } + + /** + * Gets the DXF object. + * + * @return the DXF object + */ + public DXFObject getDXFObject() { return this.obj; } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/objects/DXFMLineStyle.java b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/objects/DXFMLineStyle.java index 84a91f47e1..a3b5020d1d 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/objects/DXFMLineStyle.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/dxf/objects/DXFMLineStyle.java @@ -1,18 +1,13 @@ -/* - Copyright 2008 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFMLineStyle.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.dxf.objects; import java.util.ArrayList; @@ -22,117 +17,241 @@ import msi.gama.ext.kabeja.dxf.DXFConstants; - +/** + * The Class DXFMLineStyle. + */ public class DXFMLineStyle extends DXFObject { - protected List lines = new ArrayList(); - protected String name = ""; - protected String descrition = ""; - protected int fillColor = 256; - protected int flags = 0; - protected double startAngle = 0; - protected double endAngle = 0; - - public String getObjectType() { - return DXFConstants.OBJECT_TYPE_MLINESTYLE; - } - - public void addDXFMLineStyleElement(DXFMLineStyleElement e) { - this.lines.add(e); - } - - public DXFMLineStyleElement getDXFMLineStyleLElement(int index) { - return (DXFMLineStyleElement) this.lines.get(index); - } - - public DXFMLineStyleElement removeDXFMLineStyleLElement(int index) { - return (DXFMLineStyleElement) this.lines.remove(index); - } - - public int getDXFMLineStyleLElementCount() { - return this.lines.size(); - } - - public void sortDXFMLineStyleElements(Comparator comp) { - Collections.sort(this.lines, comp); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescrition() { - return descrition; - } - - public void setDescrition(String descrition) { - this.descrition = descrition; - } - - public int getFillColor() { - return fillColor; - } - - public void setFillColor(int fillColor) { - this.fillColor = fillColor; - } - - public int getFlags() { - return flags; - } - - public void setFlags(int flags) { - this.flags = flags; - } - - public double getStartAngle() { - return startAngle; - } - - public void setStartAngle(double startAngle) { - this.startAngle = startAngle; - } - - public double getEndAngle() { - return endAngle; - } - - public void setEndAngle(double endAngle) { - this.endAngle = endAngle; - } - - public boolean isFilled() { - return (this.flags & 1) == 1; - } - - public boolean hasStartSquareCaps() { - return (this.flags & 16) == 16; - } - - public boolean hasStartRoundCaps() { - return (this.flags & 64) == 64; - } - - public boolean hasStartInnerArcs() { - return (this.flags & 32) == 32; - } - - public boolean hasEndSquareCaps() { - return (this.flags & 256) == 256; - } - - public boolean hasEndRoundCaps() { - return (this.flags & 1024) == 1024; - } - - public boolean hasEndInnderArcs() { - return (this.flags & 512) == 512; - } - public boolean showMiters() { - return (this.flags & 2) == 2; - } + /** The lines. */ + protected List lines = new ArrayList<>(); + + /** The name. */ + protected String name = ""; + + /** The descrition. */ + protected String descrition = ""; + + /** The fill color. */ + protected int fillColor = 256; + + /** The flags. */ + protected int flags = 0; + + /** The start angle. */ + protected double startAngle = 0; + + /** The end angle. */ + protected double endAngle = 0; + + @Override + public String getObjectType() { return DXFConstants.OBJECT_TYPE_MLINESTYLE; } + + /** + * Adds the DXFM line style element. + * + * @param e + * the e + */ + public void addDXFMLineStyleElement(final DXFMLineStyleElement e) { + this.lines.add(e); + } + + /** + * Gets the DXFM line style L element. + * + * @param index + * the index + * @return the DXFM line style L element + */ + public DXFMLineStyleElement getDXFMLineStyleLElement(final int index) { + return this.lines.get(index); + } + + /** + * Removes the DXFM line style L element. + * + * @param index + * the index + * @return the DXFM line style element + */ + public DXFMLineStyleElement removeDXFMLineStyleLElement(final int index) { + return this.lines.remove(index); + } + + /** + * Gets the DXFM line style L element count. + * + * @return the DXFM line style L element count + */ + public int getDXFMLineStyleLElementCount() { return this.lines.size(); } + + /** + * Sort DXFM line style elements. + * + * @param comp + * the comp + */ + public void sortDXFMLineStyleElements(final Comparator comp) { + Collections.sort(this.lines, comp); + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { return name; } + + /** + * Sets the name. + * + * @param name + * the new name + */ + public void setName(final String name) { this.name = name; } + + /** + * Gets the descrition. + * + * @return the descrition + */ + public String getDescrition() { return descrition; } + + /** + * Sets the descrition. + * + * @param descrition + * the new descrition + */ + public void setDescrition(final String descrition) { this.descrition = descrition; } + + /** + * Gets the fill color. + * + * @return the fill color + */ + public int getFillColor() { return fillColor; } + + /** + * Sets the fill color. + * + * @param fillColor + * the new fill color + */ + public void setFillColor(final int fillColor) { this.fillColor = fillColor; } + + /** + * Gets the flags. + * + * @return the flags + */ + public int getFlags() { return flags; } + + /** + * Sets the flags. + * + * @param flags + * the new flags + */ + public void setFlags(final int flags) { this.flags = flags; } + + /** + * Gets the start angle. + * + * @return the start angle + */ + public double getStartAngle() { return startAngle; } + + /** + * Sets the start angle. + * + * @param startAngle + * the new start angle + */ + public void setStartAngle(final double startAngle) { this.startAngle = startAngle; } + + /** + * Gets the end angle. + * + * @return the end angle + */ + public double getEndAngle() { return endAngle; } + + /** + * Sets the end angle. + * + * @param endAngle + * the new end angle + */ + public void setEndAngle(final double endAngle) { this.endAngle = endAngle; } + + /** + * Checks if is filled. + * + * @return true, if is filled + */ + public boolean isFilled() { return (this.flags & 1) == 1; } + + /** + * Checks for start square caps. + * + * @return true, if successful + */ + public boolean hasStartSquareCaps() { + return (this.flags & 16) == 16; + } + + /** + * Checks for start round caps. + * + * @return true, if successful + */ + public boolean hasStartRoundCaps() { + return (this.flags & 64) == 64; + } + + /** + * Checks for start inner arcs. + * + * @return true, if successful + */ + public boolean hasStartInnerArcs() { + return (this.flags & 32) == 32; + } + + /** + * Checks for end square caps. + * + * @return true, if successful + */ + public boolean hasEndSquareCaps() { + return (this.flags & 256) == 256; + } + + /** + * Checks for end round caps. + * + * @return true, if successful + */ + public boolean hasEndRoundCaps() { + return (this.flags & 1024) == 1024; + } + + /** + * Checks for end innder arcs. + * + * @return true, if successful + */ + public boolean hasEndInnderArcs() { + return (this.flags & 512) == 512; + } + + /** + * Show miters. + * + * @return true, if successful + */ + public boolean showMiters() { + return (this.flags & 2) == 2; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFEntitiesSectionHandler.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFEntitiesSectionHandler.java index c6d81f333c..4cd1ce09a0 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFEntitiesSectionHandler.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFEntitiesSectionHandler.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFEntitiesSectionHandler.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser; import java.util.Hashtable; @@ -22,121 +17,141 @@ import msi.gama.ext.kabeja.dxf.DXFEntity; import msi.gama.ext.kabeja.parser.entities.DXFEntityHandler; - /** * @author handlers = new Hashtable<>(); + + /** The handler. */ + protected DXFEntityHandler handler = null; + + /** The parse entity. */ + protected boolean parseEntity = false; + + /** + * Instantiates a new DXF entities section handler. + */ + public DXFEntitiesSectionHandler() {} + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#getSectionKey() + */ + @Override + public String getSectionKey() { return SECTION_KEY; } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#parseGroup(int, java.lang.String) + */ + @Override + public void parseGroup(final int groupCode, final DXFValue value) { + if (groupCode == ENTITY_START) { + if (parseEntity) { + if (handler.isFollowSequence()) { + // there is a sequence like polyline + handler.parseGroup(groupCode, value); + + return; + } + endEntity(); + } + + if (handlers.containsKey(value.getValue())) { + // get handler for the new entity + handler = handlers.get(value.getValue()); + handler.setDXFDocument(this.doc); + handler.startDXFEntity(); + parseEntity = true; + } else { + // no handler found + parseEntity = false; + } + } else if (parseEntity) { handler.parseGroup(groupCode, value); } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#setDXFDocument(org.dxf2svg.xml.DXFDocument) + */ + @Override + public void setDXFDocument(final DXFDocument doc) { this.doc = doc; } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#endParsing() + */ + @Override + public void endSection() { + endEntity(); + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#startParsing() + */ + @Override + public void startSection() { + parseEntity = false; + } + + /** + * End entity. + */ + protected void endEntity() { + if (parseEntity) { + handler.endDXFEntity(); + + DXFEntity entity = handler.getDXFEntity(); + doc.addDXFEntity(entity); + } + } + + /** + * Adds the DXF entity handler. + * + * @param handler the handler + */ + public void addDXFEntityHandler(final DXFEntityHandler handler) { + handler.setDXFDocument(doc); + handlers.put(handler.getDXFEntityName(), handler); + } + + @Override + public void addHandler(final Handler handler) { + addDXFEntityHandler((DXFEntityHandler) handler); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument() + */ + @Override + public void releaseDXFDocument() { + this.doc = null; + + Iterator i = handlers.values().iterator(); + + while (i.hasNext()) { + Handler handler = (Handler) i.next(); + handler.releaseDXFDocument(); + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFObjectsSectionHandler.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFObjectsSectionHandler.java index 67f5f6e037..36760e945c 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFObjectsSectionHandler.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFObjectsSectionHandler.java @@ -1,110 +1,119 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFObjectsSectionHandler.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation + * platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser; import java.util.HashMap; import msi.gama.ext.kabeja.parser.objects.DXFObjectHandler; - /** * @author handlers = new HashMap<>(); + + /** The handler. */ + private DXFObjectHandler handler; + + /** The parse object. */ + private boolean parseObject = false; + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.DXFSectionHandler#endSection() + */ + @Override + public void endSection() { + this.endObject(); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.DXFSectionHandler#getSectionKey() + */ + @Override + public String getSectionKey() { return SECTION_KEY; } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.DXFSectionHandler#parseGroup(int, de.miethxml.kabeja.parser.DXFValue) + */ + @Override + public void parseGroup(final int groupCode, final DXFValue value) { + if (groupCode == OBJECT_START) { + this.endObject(); + + if (this.handlers.containsKey(value.getValue())) { + this.parseObject = true; + this.handler = handlers.get(value.getValue()); + this.handler.setDXFDocument(this.doc); + this.handler.startObject(); + } else { + this.parseObject = false; + } + } else if (this.parseObject) { this.handler.parseGroup(groupCode, value); } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.DXFSectionHandler#startSection() + */ + @Override + public void startSection() { + this.parseObject = false; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument() + */ + @Override + public void releaseDXFDocument() { + this.doc = null; + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.HandlerManager#addHandler(de.miethxml.kabeja.parser.Handler) + */ + @Override + public void addHandler(final Handler handler) { + DXFObjectHandler h = (DXFObjectHandler) handler; + h.setDXFDocument(this.doc); + this.handlers.put(h.getObjectType(), h); + } + + /** + * End object. + */ + protected void endObject() { + if (this.parseObject) { + // finish the old parsing object + this.handler.endObject(); + this.doc.addDXFObject(handler.getDXFObject()); + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFParser.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFParser.java index 6515d485a4..e517e63f73 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFParser.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFParser.java @@ -1,18 +1,12 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFParser.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser; import java.io.BufferedInputStream; @@ -32,266 +26,307 @@ import msi.gama.ext.kabeja.parser.dxf.filter.DXFStreamFilter; import msi.gama.ext.kabeja.tools.CodePageParser; - /** * @author = 0; i--) { - DXFStreamFilter f = (DXFStreamFilter) this.streamFilters.get(i); - f.setDXFHandler(handler); - handler = f; - } - - // the first is used filter and if no filter - // the parser itself is the filter - this.filter = handler; - } - - public String getName() { - return PARSER_NAME; - } + + /** The Constant PARSER_NAME. */ + public final static String PARSER_NAME = "DXFParser"; + + /** The Constant EXTENSION. */ + public final static String EXTENSION = "dxf"; + + /** The Constant SECTION_START. */ + private final static String SECTION_START = "SECTION"; + + /** The Constant SECTION_END. */ + private final static String SECTION_END = "ENDSEC"; + + /** The Constant END_STREAM. */ + private final static String END_STREAM = "EOF"; + + /** The Constant COMMAND_CODE. */ + private final static int COMMAND_CODE = 0; + + /** The Constant DEFAULT_ENCODING. */ + public static final String DEFAULT_ENCODING = ""; + + /** The doc. */ + protected DXFDocument doc; + + /** The handlers. */ + protected Hashtable handlers = new Hashtable<>(); + + /** The current handler. */ + protected DXFSectionHandler currentHandler; + + /** The line. */ + private String line; + + /** The stream filters. */ + protected List streamFilters = new ArrayList<>(); + + /** The filter. */ + protected DXFHandler filter; + + /** The key. */ + // some parse flags + private boolean key = false; + + /** The sectionstarts. */ + private boolean sectionstarts = false; + + /** The linecount. */ + private int linecount; + + /** The parse. */ + private boolean parse = false; + + /** + * Instantiates a new DXF parser. + */ + public DXFParser() {} + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Parser#parse(java.lang.String) + */ + @Override + public void parse(final String file) throws ParseException { + parse(file, DEFAULT_ENCODING); + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Parser#parse(java.lang.String, java.lang.String) + */ + @Override + public void parse(final String file, final String encoding) throws ParseException { + try { + parse(new FileInputStream(file), encoding); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Parser#parse(java.io.InputStream, java.lang.String) + */ + @Override + public void parse(final InputStream input, String encoding) throws ParseException { + String currentKey = ""; + key = false; + linecount = 0; + parse = false; + + // initialize + doc = new DXFDocument(); + doc.setProperty(DXFDocument.PROPERTY_ENCODING, encoding); + // the StreamFilters + this.buildFilterChain(); + + @SuppressWarnings ("resource") BufferedReader in = null; + try { + if ("".equals(encoding)) { + BufferedInputStream buf = new BufferedInputStream(input); + buf.mark(9000); + + try { + BufferedReader r = new BufferedReader(new InputStreamReader(buf)); + CodePageParser p = new CodePageParser(); + encoding = p.parseEncoding(r); + buf.reset(); + in = new BufferedReader(new InputStreamReader(buf, encoding)); + } catch (IOException e1) { + buf.reset(); + in = new BufferedReader(new InputStreamReader(buf)); + } + } else { + in = new BufferedReader(new InputStreamReader(input, encoding)); + } + + key = true; + sectionstarts = false; + + while ((line = in.readLine()) != null) { + linecount++; + + if (key) { + currentKey = line; + key = false; + } else { + int keyCode = Integer.parseInt(currentKey.trim()); + // the filter chain + filter.parseGroup(keyCode, new DXFValue(line.trim())); + // parseGroup(currentKey, line); + key = true; + } + } + + in.close(); + + in = null; + + // finish last parsing + if (parse) { currentHandler.endSection(); } + } catch (IOException ioe) { + throw new ParseException(ioe.toString()); + } + } + + @Override + public void parseGroup(final int keyCode, final DXFValue value) throws ParseException { + // System.out.println(""+keyCode); + // System.out.println(" "+value.getValue()); + try { + if (sectionstarts) { + sectionstarts = false; + + if (handlers.containsKey(value.getValue())) { + currentHandler = handlers.get(value.getValue()); + parse = true; + currentHandler.setDXFDocument(doc); + currentHandler.startSection(); + } else { + parse = false; + } + + return; + } + + if (keyCode == COMMAND_CODE && SECTION_START.equals(value.getValue()) && !sectionstarts) { + sectionstarts = true; + } + + if (keyCode == COMMAND_CODE && SECTION_END.equals(value.getValue())) { + if (parse) { currentHandler.endSection(); } + + parse = false; + + return; + } + + if (parse) { currentHandler.parseGroup(keyCode, value); } + } catch (NumberFormatException e) { + e.printStackTrace(); + throw new ParseException("Line: " + linecount + " unsupported groupcode: " + key + " for value:" + value, + e); + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Parser#getDocument() + */ + @Override + public DXFDocument getDocument() { return doc; } + + /** + * Adds the DXF section handler. + * + * @param handler + * the handler + */ + public void addDXFSectionHandler(final DXFSectionHandler handler) { + handler.setDXFDocument(doc); + handlers.put(handler.getSectionKey(), handler); + } + + @Override + public void addHandler(final Handler handler) { + addDXFSectionHandler((DXFSectionHandler) handler); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument() + */ + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Parser#releaseDXFDocument() + */ + @Override + public void releaseDXFDocument() { + this.doc = null; + + Iterator i = handlers.values().iterator(); + + while (i.hasNext()) { + Handler handler = (Handler) i.next(); + handler.releaseDXFDocument(); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#setDXFDocument(de.miethxml.kabeja.dxf.DXFDocument) + */ + + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Parser#setDXFDocument(org.kabeja.dxf.DXFDocument) + */ + @Override + public void setDXFDocument(final DXFDocument doc) { this.doc = doc; } + + @Override + public boolean supportedExtension(final String extension) { + return EXTENSION.equals(extension.toLowerCase()); + } + + /** + * Adds the DXF stream filter. + * + * @param filter + * the filter + */ + public void addDXFStreamFilter(final DXFStreamFilter filter) { + this.streamFilters.add(filter); + } + + /** + * Removes the DXF stream filter. + * + * @param filter + * the filter + */ + public void removeDXFStreamFilter(final DXFStreamFilter filter) { + this.streamFilters.remove(filter); + } + + /** + * Builds the filter chain. + */ + protected void buildFilterChain() { + // build the chain from end to start + // the parser itself is the last element + // in the chain + DXFHandler handler = this; + + for (int i = this.streamFilters.size() - 1; i >= 0; i--) { + DXFStreamFilter f = this.streamFilters.get(i); + f.setDXFHandler(handler); + handler = f; + } + + // the first is used filter and if no filter + // the parser itself is the filter + this.filter = handler; + } + + @Override + public String getName() { return PARSER_NAME; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFTableSectionHandler.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFTableSectionHandler.java index 874e501c72..d6e3386ce3 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFTableSectionHandler.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/DXFTableSectionHandler.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFTableSectionHandler.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser; import java.util.Hashtable; @@ -20,109 +15,129 @@ import msi.gama.ext.kabeja.parser.table.DXFTableHandler; - /** * @author handlers = new Hashtable<>(); + + /** The parse. */ + private boolean parse = false; + + /** + * Instantiates a new DXF table section handler. + */ + public DXFTableSectionHandler() {} + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#getSectionKey() + */ + @Override + public String getSectionKey() { return sectionKey; } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#parseGroup(int, java.lang.String) + */ + @Override + public void parseGroup(final int groupCode, final DXFValue value) { + if (groupCode == TABLE_CODE) { + // switch table + if (TABLE_END.equals(value.toString())) { + table = ""; + + if (parse) { + handler.endParsing(); + parse = false; + } + } else if (TABLE_START.equals(value.toString())) {} else { + if (parse) { handler.endParsing(); } + + table = value.getValue(); + + if (handlers.containsKey(table)) { + handler = handlers.get(table); + handler.setDXFDocument(this.doc); + handler.startParsing(); + parse = true; + } else { + parse = false; + } + } + } else if (parse) { handler.parseGroup(groupCode, value); } + } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#endParsing() + */ + @Override + public void endSection() {} + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.SectionHandler#startParsing() + */ + @Override + public void startSection() { + parse = false; + } + + @Override + public void addHandler(final Handler handler) { + addDXFTableHandler((DXFTableHandler) handler); + } + + /** + * Adds the DXF table handler. + * + * @param handler + * the handler + */ + public void addDXFTableHandler(final DXFTableHandler handler) { + handlers.put(handler.getTableKey(), handler); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.Handler#releaseDXFDocument() + */ + @Override + public void releaseDXFDocument() { + this.doc = null; + + Iterator i = handlers.values().iterator(); + + while (i.hasNext()) { + Handler handler = (Handler) i.next(); + handler.releaseDXFDocument(); + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/SAXParserBuilder.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/SAXParserBuilder.java index e3f991d2c4..e3eaf64bfa 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/SAXParserBuilder.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/SAXParserBuilder.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * SAXParserBuilder.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser; import java.io.IOException; @@ -27,7 +22,6 @@ import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; - /** * Build a Parser from XML stream with the following format: * @@ -73,193 +67,197 @@ * */ public class SAXParserBuilder implements ContentHandler { - public static String ELEMENT_PARSER = "parser"; - public static String ELEMENT_HANDLER = "handler"; - public static String ELEMENT_HANDLERS = "handlers"; - public static String ATTRIBUTE_CLASS = "class"; - public static String ATTRIBUTE_EXTENSIONS = "extensions"; - public static String XMLNS_KABEJA_PARSER = "http://kabeja.org/parser/1.0"; - private Parser parser; - private Stack stack = new Stack(); - private HandlerManager currentHandlerManager; - private Handler handler; - - public SAXParserBuilder() { - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#characters(char[], int, int) - */ - public void characters(char[] ch, int start, int length) - throws SAXException { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#endDocument() - */ - public void endDocument() throws SAXException { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#endElement(java.lang.String, - * java.lang.String, java.lang.String) - */ - public void endElement(String namespaceURI, String localName, String qName) - throws SAXException { - if (localName.equals(ELEMENT_HANDLERS) && - namespaceURI.equals(XMLNS_KABEJA_PARSER)) { - currentHandlerManager = (HandlerManager) stack.pop(); - } - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) - */ - public void endPrefixMapping(String prefix) throws SAXException { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) - */ - public void ignorableWhitespace(char[] ch, int start, int length) - throws SAXException { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, - * java.lang.String) - */ - public void processingInstruction(String target, String data) - throws SAXException { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) - */ - public void setDocumentLocator(Locator locator) { - // TODO Auto-generated method stub - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) - */ - public void skippedEntity(String name) throws SAXException { - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#startDocument() - */ - public void startDocument() throws SAXException { - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#startElement(java.lang.String, - * java.lang.String, java.lang.String, org.xml.sax.Attributes) - */ - public void startElement(String namespaceURI, String localName, - String qName, Attributes atts) throws SAXException { - if (namespaceURI.equals(XMLNS_KABEJA_PARSER)) { - if (localName.equals(ELEMENT_HANDLER)) { - String clazz = atts.getValue(ATTRIBUTE_CLASS); - - try { - // load the class and add to the currentHandlerManager - Class c = this.getClass().getClassLoader().loadClass(clazz); - handler = (Handler) c.newInstance(); - currentHandlerManager.addHandler(handler); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } else if (localName.equals(ELEMENT_HANDLERS)) { - stack.add(currentHandlerManager); - currentHandlerManager = (HandlerManager) handler; - } else if (localName.equals(ELEMENT_PARSER)) { - String clazz = atts.getValue(ATTRIBUTE_CLASS); - - try { - // load the class and add to the currentHandlerManager - Class c = this.getClass().getClassLoader().loadClass(clazz); - this.parser = (Parser) c.newInstance(); - - if (this.parser instanceof HandlerManager) { - this.currentHandlerManager = (HandlerManager) this.parser; - } - - this.stack = new Stack(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - } - } - - /* - * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, - * java.lang.String) - */ - public void startPrefixMapping(String prefix, String uri) - throws SAXException { - // TODO Auto-generated method stub - } - - public Parser getParser() { - return parser; - } - - /** - * - * @param in - * the InputStream - * @return The DXFParser build from the XML description - */ - public static Parser buildFromStream(InputStream in) { - SAXParserBuilder builder = new SAXParserBuilder(); - - try { - XMLReader parser = XMLReaderFactory.createXMLReader(); - parser.setFeature("http://apache.org/xml/features/xinclude", true); - parser.setContentHandler(builder); - parser.parse(new InputSource(in)); - } catch (SAXException e) { - System.err.println(e.getMessage()); - } catch (IOException ioe) { - } - - return builder.getParser(); - } + + /** The element parser. */ + public static String ELEMENT_PARSER = "parser"; + + /** The element handler. */ + public static String ELEMENT_HANDLER = "handler"; + + /** The element handlers. */ + public static String ELEMENT_HANDLERS = "handlers"; + + /** The attribute class. */ + public static String ATTRIBUTE_CLASS = "class"; + + /** The attribute extensions. */ + public static String ATTRIBUTE_EXTENSIONS = "extensions"; + + /** The xmlns kabeja parser. */ + public static String XMLNS_KABEJA_PARSER = "http://kabeja.org/parser/1.0"; + + /** The parser. */ + private Parser parser; + + /** The stack. */ + private Stack stack = new Stack<>(); + + /** The current handler manager. */ + private HandlerManager currentHandlerManager; + + /** The handler. */ + private Handler handler; + + /** + * Instantiates a new SAX parser builder. + */ + public SAXParserBuilder() {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#characters(char[], int, int) + */ + @Override + public void characters(final char[] ch, final int start, final int length) throws SAXException {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endDocument() + */ + @Override + public void endDocument() throws SAXException {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException { + if (localName.equals(ELEMENT_HANDLERS) && namespaceURI.equals(XMLNS_KABEJA_PARSER)) { + currentHandlerManager = stack.pop(); + } + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) + */ + @Override + public void endPrefixMapping(final String prefix) throws SAXException {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) + */ + @Override + public void ignorableWhitespace(final char[] ch, final int start, final int length) throws SAXException {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) + */ + @Override + public void processingInstruction(final String target, final String data) throws SAXException {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) + */ + @Override + public void setDocumentLocator(final Locator locator) {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) + */ + @Override + public void skippedEntity(final String name) throws SAXException {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startDocument() + */ + @Override + public void startDocument() throws SAXException {} + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, + * org.xml.sax.Attributes) + */ + @Override + public void startElement(final String namespaceURI, final String localName, final String qName, + final Attributes atts) throws SAXException { + if (namespaceURI.equals(XMLNS_KABEJA_PARSER)) { + if (localName.equals(ELEMENT_HANDLER)) { + String clazz = atts.getValue(ATTRIBUTE_CLASS); + + try { + // load the class and add to the currentHandlerManager + Class c = this.getClass().getClassLoader().loadClass(clazz); + handler = (Handler) c.newInstance(); + currentHandlerManager.addHandler(handler); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + } else if (localName.equals(ELEMENT_HANDLERS)) { + stack.add(currentHandlerManager); + currentHandlerManager = (HandlerManager) handler; + } else if (localName.equals(ELEMENT_PARSER)) { + String clazz = atts.getValue(ATTRIBUTE_CLASS); + + try { + // load the class and add to the currentHandlerManager + Class c = this.getClass().getClassLoader().loadClass(clazz); + this.parser = (Parser) c.newInstance(); + + if (this.parser instanceof HandlerManager) { + this.currentHandlerManager = (HandlerManager) this.parser; + } + + this.stack = new Stack<>(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { + e.printStackTrace(); + } + } + } + } + + /* + * (non-Javadoc) + * + * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) + */ + @Override + public void startPrefixMapping(final String prefix, final String uri) throws SAXException { + // TODO Auto-generated method stub + } + + /** + * Gets the parser. + * + * @return the parser + */ + public Parser getParser() { return parser; } + + /** + * + * @param in + * the InputStream + * @return The DXFParser build from the XML description + */ + public static Parser buildFromStream(final InputStream in) { + SAXParserBuilder builder = new SAXParserBuilder(); + + try { + XMLReader parser = XMLReaderFactory.createXMLReader(); + parser.setFeature("http://apache.org/xml/features/xinclude", true); + parser.setContentHandler(builder); + parser.parse(new InputSource(in)); + } catch (SAXException e) { + System.err.println(e.getMessage()); + } catch (IOException ioe) {} + + return builder.getParser(); + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/DXFStreamLayerFilter.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/DXFStreamLayerFilter.java index 4e9646c73a..98d9a09562 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/DXFStreamLayerFilter.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/DXFStreamLayerFilter.java @@ -1,18 +1,13 @@ -/* - Copyright 2008 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * DXFStreamLayerFilter.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser.dxf.filter; import java.util.ArrayList; @@ -25,91 +20,131 @@ import msi.gama.ext.kabeja.parser.DXFValue; import msi.gama.ext.kabeja.parser.ParseException; - +/** + * The Class DXFStreamLayerFilter. + */ public class DXFStreamLayerFilter extends DXFStreamEntityFilter { - public final static String PROPERTY_LAYERS_EXCLUDE = "layers.exclude"; - public final static String PROPERTY_LAYERS_INCLUDE = "layers.include"; - public final static int LAYER_NAME = 8; - protected List parseValues = new ArrayList(); - protected Set exclude = new HashSet(); - protected Set include = new HashSet(); - protected String layer = ""; - boolean findLayer = true; - - public void setProperties(Map properties) { - if (properties.containsKey(PROPERTY_LAYERS_INCLUDE)) { - this.include.clear(); - - StringTokenizer st = new StringTokenizer((String) properties.get( - PROPERTY_LAYERS_INCLUDE), "|"); - - while (st.hasMoreTokens()) { - String layer = st.nextToken(); - - this.include.add(layer); - } - } - - if (properties.containsKey(PROPERTY_LAYERS_EXCLUDE)) { - this.exclude.clear(); - - StringTokenizer st = new StringTokenizer((String) properties.get( - PROPERTY_LAYERS_EXCLUDE), "|"); - - while (st.hasMoreTokens()) { - this.exclude.add(st.nextToken()); - } - } - } - - protected void endEntity() throws ParseException { - if (include.contains(this.layer)) { - this.outputEntity(); - } else if (!exclude.contains(this.layer)) { - this.outputEntity(); - } - } - - protected void outputEntity() throws ParseException { - // give the complete entity to the next handler - for (int i = 0; i < this.parseValues.size(); i++) { - ParseValue v = (ParseValue) this.parseValues.get(i); - this.handler.parseGroup(v.getGroupCode(), v.getDXFValue()); - } - } - - protected void startEntity(String type) throws ParseException { - this.parseValues.clear(); - this.findLayer = true; - } - - protected void parseEntity(int groupCode, DXFValue value) - throws ParseException { - if (this.findLayer && (groupCode == LAYER_NAME)) { - this.layer = value.getValue(); - this.findLayer = false; - } - - //parse values to buffer - ParseValue v = new ParseValue(groupCode, value); - this.parseValues.add(v); - } - - private class ParseValue { - int groupCode; - DXFValue value; - - public ParseValue(int groupCode, DXFValue value) { - this.groupCode = groupCode; - this.value = value; - } - - public int getGroupCode() { - return this.groupCode; - } - - public DXFValue getDXFValue() { - return this.value; - } - } + + /** The Constant PROPERTY_LAYERS_EXCLUDE. */ + public final static String PROPERTY_LAYERS_EXCLUDE = "layers.exclude"; + + /** The Constant PROPERTY_LAYERS_INCLUDE. */ + public final static String PROPERTY_LAYERS_INCLUDE = "layers.include"; + + /** The Constant LAYER_NAME. */ + public final static int LAYER_NAME = 8; + + /** The parse values. */ + protected List parseValues = new ArrayList<>(); + + /** The exclude. */ + protected Set exclude = new HashSet<>(); + + /** The include. */ + protected Set include = new HashSet<>(); + + /** The layer. */ + protected String layer = ""; + + /** The find layer. */ + boolean findLayer = true; + + @Override + public void setProperties(final Map properties) { + if (properties.containsKey(PROPERTY_LAYERS_INCLUDE)) { + this.include.clear(); + + StringTokenizer st = new StringTokenizer((String) properties.get(PROPERTY_LAYERS_INCLUDE), "|"); + + while (st.hasMoreTokens()) { + String layer = st.nextToken(); + + this.include.add(layer); + } + } + + if (properties.containsKey(PROPERTY_LAYERS_EXCLUDE)) { + this.exclude.clear(); + + StringTokenizer st = new StringTokenizer((String) properties.get(PROPERTY_LAYERS_EXCLUDE), "|"); + + while (st.hasMoreTokens()) { this.exclude.add(st.nextToken()); } + } + } + + @Override + protected void endEntity() throws ParseException { + if (include.contains(this.layer) || !exclude.contains(this.layer)) { this.outputEntity(); } + } + + /** + * Output entity. + * + * @throws ParseException + * the parse exception + */ + protected void outputEntity() throws ParseException { + // give the complete entity to the next handler + for (Object element : this.parseValues) { + ParseValue v = (ParseValue) element; + this.handler.parseGroup(v.getGroupCode(), v.getDXFValue()); + } + } + + @Override + protected void startEntity(final String type) throws ParseException { + this.parseValues.clear(); + this.findLayer = true; + } + + @Override + protected void parseEntity(final int groupCode, final DXFValue value) throws ParseException { + if (this.findLayer && groupCode == LAYER_NAME) { + this.layer = value.getValue(); + this.findLayer = false; + } + + // parse values to buffer + ParseValue v = new ParseValue(groupCode, value); + this.parseValues.add(v); + } + + /** + * The Class ParseValue. + */ + private static class ParseValue { + + /** The group code. */ + int groupCode; + + /** The value. */ + DXFValue value; + + /** + * Instantiates a new parses the value. + * + * @param groupCode + * the group code + * @param value + * the value + */ + public ParseValue(final int groupCode, final DXFValue value) { + this.groupCode = groupCode; + this.value = value; + } + + /** + * Gets the group code. + * + * @return the group code + */ + public int getGroupCode() { return this.groupCode; } + + /** + * Gets the DXF value. + * + * @return the DXF value + */ + public DXFValue getDXFValue() { return this.value; } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/FilterExample.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/FilterExample.java index 0f382a25ad..820b8b416a 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/FilterExample.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/dxf/filter/FilterExample.java @@ -1,49 +1,45 @@ -/* - Copyright 2008 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * FilterExample.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser.dxf.filter; import java.util.HashMap; import java.util.Map; -import msi.gama.ext.kabeja.dxf.DXFDocument; import msi.gama.ext.kabeja.parser.DXFParser; import msi.gama.ext.kabeja.parser.ParserBuilder; - +/** + * The Class FilterExample. + */ public class FilterExample { - /** - * @param args - */ - public static void main(String[] args) { - try { - DXFParser parser = (DXFParser) ParserBuilder.createDefaultParser(); - - //test - DXFStreamFilter filter = new DXFStreamLayerFilter(); - Map p = new HashMap(); - p.put("layers.include", args[0]); - filter.setProperties(p); - parser.addDXFStreamFilter(filter); - parser.parse(args[1]); - - DXFDocument doc = parser.getDocument(); - - //do something with the doc - } catch (Exception e) { - e.printStackTrace(); - } - } + /** + * @param args + */ + public static void main(final String[] args) { + try { + DXFParser parser = (DXFParser) ParserBuilder.createDefaultParser(); + + // test + DXFStreamFilter filter = new DXFStreamLayerFilter(); + Map p = new HashMap<>(); + p.put("layers.include", args[0]); + filter.setProperties(p); + parser.addDXFStreamFilter(filter); + parser.parse(args[1]); + + // DXFDocument doc = parser.getDocument(); + + // do something with the doc + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/entities/DXFHatchHandler.java b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/entities/DXFHatchHandler.java index 0eb9c89b2e..5461032a9a 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/parser/entities/DXFHatchHandler.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/parser/entities/DXFHatchHandler.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * DXFHatchHandler.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.parser.entities; import java.util.Hashtable; @@ -29,385 +24,488 @@ import msi.gama.ext.kabeja.dxf.helpers.HatchLineFamily; import msi.gama.ext.kabeja.parser.DXFValue; - /** * @author Simon Mieth * */ public class DXFHatchHandler extends AbstractEntityHandler { - public static final String END_SEQUENCE = "SEQEND"; - public static final int END_SEQUENCE_CODE = -2; - public static final int GROUPCODE_ASSOSIATIVITY_FLAG = 71; - public static final int GROUPCODE_BOUNDARY_ANNOTATION = 73; - public static final int GROUPCODE_BOUNDARY_EDGE_COUNT = 93; - public static final int GROUPCODE_BOUNDARY_EDGE_TYPE = 72; - public static final int GROUPCODE_BOUNDARY_LOOP_COUNT = 91; - public static final int GROUPCODE_BOUNDAYY_LOOP_TYPE = 92; - public static final int GROUPCODE_DEFINITION_LINE_COUNT = 78; - public static final int GROUPCODE_DEGENERTE_BOUNDARY_PATH_COUNT = 99; - public static final int GROUPCODE_HATCH_DOUBLE_FLAG = 77; - public static final int GROUPCODE_HATCH_STYLE = 75; - public static final int GROUPCODE_NAME = 2; - public static final int GROUPCODE_OFFSET_VECTOR = 11; - public static final int GROUPCODE_PATTERN_ANGLE = 52; - public static final int GROUPCODE_PATTERN_BASE_X = 43; - public static final int GROUPCODE_PATTERN_BASE_Y = 44; - public static final int GROUPCODE_PATTERN_FILL_COLOR = 63; - public static final int GROUPCODE_PATTERN_LINE_ANGLE = 53; - public static final int GROUPCODE_PATTERN_LINE_COUNT = 79; - public static final int GROUPCODE_PATTERN_LINE_TYPE_DATA = 49; - public static final int GROUPCODE_PATTERN_OFFSET_X = 45; - public static final int GROUPCODE_PATTERN_OFFSET_Y = 46; - public static final int GROUPCODE_PATTERN_SCALE = 41; - public static final int GROUPCODE_PATTERN_TYPE = 76; - public static final int GROUPCODE_PIXEL_SIZE = 47; - public static final int GROUPCODE_SEED_POINTS_COUNT = 98; - public static final int GROUPCODE_SOLID_FILL_FLAG = 70; - protected DXFEntityHandler boundaryHandler; - protected Hashtable boundaryHandlers = new Hashtable(); - protected int count; - private boolean follow = false; - private DXFHatch hatch; - protected HatchLineFamily linePattern = new HatchLineFamily(); - protected HatchBoundaryLoop loop; - protected double[] parameters = new double[0]; - private boolean parseBoundary = false; - protected DXFHatchPattern pattern; - protected DXFPolyline polyline; - private boolean polylineBoundary = false; - protected DXFVertex vertex; - protected int lastGroupCode; - - public DXFHatchHandler() { - init(); - } - - protected void endBoundaryElement() { - if (boundaryHandler != null) { - // get the last parsed entity - this.boundaryHandler.endDXFEntity(); - this.loop.addBoundaryEdge(boundaryHandler.getDXFEntity()); - this.boundaryHandler = null; - } - } - - /* - * (non-Javadoc) - * - * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() - */ - public void endDXFEntity() { - // this.linePattern.setPattern(this.parameters); - if (this.pattern != null) { - this.hatch.setDXFHatchPatternID(this.pattern.getID()); - } - } - - /* - * (non-Javadoc) - * - * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() - */ - public DXFEntity getDXFEntity() { - return hatch; - } - - /* - * (non-Javadoc) - * - * @see org.dxf2svg.parser.entities.DXFEntityHandler#getDXFEntityName() - */ - public String getDXFEntityName() { - return DXFConstants.ENTITY_TYPE_HATCH; - } - - protected void init() { - DXFEntityHandler handler = new DXFSplineHandler(); - boundaryHandlers.put(handler.getDXFEntityName(), handler); - - handler = new DXFLineHandler(); - boundaryHandlers.put(handler.getDXFEntityName(), handler); - - handler = new DXFArcHandler(); - boundaryHandlers.put(handler.getDXFEntityName(), handler); - - handler = new DXFEllipseHandler(); - boundaryHandlers.put(handler.getDXFEntityName(), handler); - } - - /* - * (non-Javadoc) - * - * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() - */ - public boolean isFollowSequence() { - return false; - } - - protected void parseBoundary(int groupCode, DXFValue value) { - if (this.polylineBoundary) { - parsePolylineBoundary(groupCode, value); - } else { - // delegate to the entityhandler - this.boundaryHandler.parseGroup(groupCode, value); - } - } - - /* - * (non-Javadoc) - * - * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, - * de.miethxml.kabeja.parser.DXFValue) - */ - public void parseGroup(int groupCode, DXFValue value) { - switch (groupCode) { - case GROUPCODE_BOUNDARY_LOOP_COUNT: - break; - - case GROUPCODE_BOUNDARY_EDGE_COUNT: - break; - - case GROUPCODE_BOUNDARY_EDGE_TYPE: - - if (this.lastGroupCode == GROUPCODE_BOUNDAYY_LOOP_TYPE) { - this.polylineBoundary = true; - this.polyline = new DXFPolyline(); - this.polyline.setDXFDocument(this.doc); - this.loop.addBoundaryEdge(this.polyline); - - break; - } - - if (!this.polylineBoundary) { - this.endBoundaryElement(); - - switch (value.getIntegerValue()) { - case 1: - boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_LINE); - boundaryHandler.startDXFEntity(); - - break; - - case 2: - boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_ARC); - boundaryHandler.startDXFEntity(); - - break; - - case 3: - boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_ELLIPSE); - boundaryHandler.startDXFEntity(); - - break; - case 4: - boundaryHandler = (DXFEntityHandler) boundaryHandlers.get(DXFConstants.ENTITY_TYPE_SPLINE); - boundaryHandler.startDXFEntity(); + /** The Constant END_SEQUENCE. */ + public static final String END_SEQUENCE = "SEQEND"; + + /** The Constant END_SEQUENCE_CODE. */ + public static final int END_SEQUENCE_CODE = -2; + + /** The Constant GROUPCODE_ASSOSIATIVITY_FLAG. */ + public static final int GROUPCODE_ASSOSIATIVITY_FLAG = 71; + + /** The Constant GROUPCODE_BOUNDARY_ANNOTATION. */ + public static final int GROUPCODE_BOUNDARY_ANNOTATION = 73; + + /** The Constant GROUPCODE_BOUNDARY_EDGE_COUNT. */ + public static final int GROUPCODE_BOUNDARY_EDGE_COUNT = 93; + + /** The Constant GROUPCODE_BOUNDARY_EDGE_TYPE. */ + public static final int GROUPCODE_BOUNDARY_EDGE_TYPE = 72; + + /** The Constant GROUPCODE_BOUNDARY_LOOP_COUNT. */ + public static final int GROUPCODE_BOUNDARY_LOOP_COUNT = 91; + + /** The Constant GROUPCODE_BOUNDAYY_LOOP_TYPE. */ + public static final int GROUPCODE_BOUNDAYY_LOOP_TYPE = 92; + + /** The Constant GROUPCODE_DEFINITION_LINE_COUNT. */ + public static final int GROUPCODE_DEFINITION_LINE_COUNT = 78; + + /** The Constant GROUPCODE_DEGENERTE_BOUNDARY_PATH_COUNT. */ + public static final int GROUPCODE_DEGENERTE_BOUNDARY_PATH_COUNT = 99; + + /** The Constant GROUPCODE_HATCH_DOUBLE_FLAG. */ + public static final int GROUPCODE_HATCH_DOUBLE_FLAG = 77; + + /** The Constant GROUPCODE_HATCH_STYLE. */ + public static final int GROUPCODE_HATCH_STYLE = 75; + + /** The Constant GROUPCODE_NAME. */ + public static final int GROUPCODE_NAME = 2; + + /** The Constant GROUPCODE_OFFSET_VECTOR. */ + public static final int GROUPCODE_OFFSET_VECTOR = 11; + + /** The Constant GROUPCODE_PATTERN_ANGLE. */ + public static final int GROUPCODE_PATTERN_ANGLE = 52; + + /** The Constant GROUPCODE_PATTERN_BASE_X. */ + public static final int GROUPCODE_PATTERN_BASE_X = 43; + + /** The Constant GROUPCODE_PATTERN_BASE_Y. */ + public static final int GROUPCODE_PATTERN_BASE_Y = 44; + + /** The Constant GROUPCODE_PATTERN_FILL_COLOR. */ + public static final int GROUPCODE_PATTERN_FILL_COLOR = 63; + + /** The Constant GROUPCODE_PATTERN_LINE_ANGLE. */ + public static final int GROUPCODE_PATTERN_LINE_ANGLE = 53; + + /** The Constant GROUPCODE_PATTERN_LINE_COUNT. */ + public static final int GROUPCODE_PATTERN_LINE_COUNT = 79; + + /** The Constant GROUPCODE_PATTERN_LINE_TYPE_DATA. */ + public static final int GROUPCODE_PATTERN_LINE_TYPE_DATA = 49; + + /** The Constant GROUPCODE_PATTERN_OFFSET_X. */ + public static final int GROUPCODE_PATTERN_OFFSET_X = 45; + + /** The Constant GROUPCODE_PATTERN_OFFSET_Y. */ + public static final int GROUPCODE_PATTERN_OFFSET_Y = 46; + + /** The Constant GROUPCODE_PATTERN_SCALE. */ + public static final int GROUPCODE_PATTERN_SCALE = 41; + + /** The Constant GROUPCODE_PATTERN_TYPE. */ + public static final int GROUPCODE_PATTERN_TYPE = 76; + + /** The Constant GROUPCODE_PIXEL_SIZE. */ + public static final int GROUPCODE_PIXEL_SIZE = 47; + + /** The Constant GROUPCODE_SEED_POINTS_COUNT. */ + public static final int GROUPCODE_SEED_POINTS_COUNT = 98; + + /** The Constant GROUPCODE_SOLID_FILL_FLAG. */ + public static final int GROUPCODE_SOLID_FILL_FLAG = 70; + + /** The boundary handler. */ + protected DXFEntityHandler boundaryHandler; + + /** The boundary handlers. */ + protected Hashtable boundaryHandlers = new Hashtable<>(); + + /** The count. */ + protected int count; + + /** The follow. */ + // private final boolean follow = false; + + /** The hatch. */ + private DXFHatch hatch; + + /** The line pattern. */ + protected HatchLineFamily linePattern = new HatchLineFamily(); + + /** The loop. */ + protected HatchBoundaryLoop loop; + + /** The parameters. */ + protected double[] parameters = {}; + + /** The parse boundary. */ + private boolean parseBoundary = false; + + /** The pattern. */ + protected DXFHatchPattern pattern; + + /** The polyline. */ + protected DXFPolyline polyline; + + /** The polyline boundary. */ + private boolean polylineBoundary = false; + + /** The vertex. */ + protected DXFVertex vertex; + + /** The last group code. */ + protected int lastGroupCode; + + /** + * Instantiates a new DXF hatch handler. + */ + public DXFHatchHandler() { + init(); + } + + /** + * End boundary element. + */ + protected void endBoundaryElement() { + if (boundaryHandler != null) { + // get the last parsed entity + this.boundaryHandler.endDXFEntity(); + this.loop.addBoundaryEdge(boundaryHandler.getDXFEntity()); + this.boundaryHandler = null; + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#endDXFEntity() + */ + @Override + public void endDXFEntity() { + // this.linePattern.setPattern(this.parameters); + if (this.pattern != null) { this.hatch.setDXFHatchPatternID(this.pattern.getID()); } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#getDXFEntity() + */ + @Override + public DXFEntity getDXFEntity() { return hatch; } + + /* + * (non-Javadoc) + * + * @see org.dxf2svg.parser.entities.DXFEntityHandler#getDXFEntityName() + */ + @Override + public String getDXFEntityName() { return DXFConstants.ENTITY_TYPE_HATCH; } + + /** + * Inits the. + */ + protected void init() { + DXFEntityHandler handler = new DXFSplineHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + + handler = new DXFLineHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + + handler = new DXFArcHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + + handler = new DXFEllipseHandler(); + boundaryHandlers.put(handler.getDXFEntityName(), handler); + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#isFollowSequence() + */ + @Override + public boolean isFollowSequence() { return false; } + + /** + * Parses the boundary. + * + * @param groupCode + * the group code + * @param value + * the value + */ + protected void parseBoundary(final int groupCode, final DXFValue value) { + if (this.polylineBoundary) { + parsePolylineBoundary(groupCode, value); + } else { + // delegate to the entityhandler + this.boundaryHandler.parseGroup(groupCode, value); + } + } + + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#parseGroup(int, de.miethxml.kabeja.parser.DXFValue) + */ + @Override + public void parseGroup(final int groupCode, final DXFValue value) { + switch (groupCode) { + case GROUPCODE_BOUNDARY_LOOP_COUNT: + break; + + case GROUPCODE_BOUNDARY_EDGE_COUNT: + break; + + case GROUPCODE_BOUNDARY_EDGE_TYPE: + + if (this.lastGroupCode == GROUPCODE_BOUNDAYY_LOOP_TYPE) { + this.polylineBoundary = true; + this.polyline = new DXFPolyline(); + this.polyline.setDXFDocument(this.doc); + this.loop.addBoundaryEdge(this.polyline); + + break; + } + + if (!this.polylineBoundary) { + this.endBoundaryElement(); + + switch (value.getIntegerValue()) { + case 1: + boundaryHandler = boundaryHandlers.get(DXFConstants.ENTITY_TYPE_LINE); + boundaryHandler.startDXFEntity(); + + break; + + case 2: + boundaryHandler = boundaryHandlers.get(DXFConstants.ENTITY_TYPE_ARC); + boundaryHandler.startDXFEntity(); + + break; + + case 3: + boundaryHandler = boundaryHandlers.get(DXFConstants.ENTITY_TYPE_ELLIPSE); + boundaryHandler.startDXFEntity(); + + break; + + case 4: + boundaryHandler = boundaryHandlers.get(DXFConstants.ENTITY_TYPE_SPLINE); + boundaryHandler.startDXFEntity(); - break; - } - } + break; + } + } - break; + break; - case GROUPCODE_BOUNDAYY_LOOP_TYPE: + case GROUPCODE_BOUNDAYY_LOOP_TYPE: - // finish up last parsing - if (!this.polylineBoundary) { - this.endBoundaryElement(); - } + // finish up last parsing + if (!this.polylineBoundary) { this.endBoundaryElement(); } - // a new loop starts - this.loop = new HatchBoundaryLoop(); - this.hatch.addBoundaryLoop(loop); + // a new loop starts + this.loop = new HatchBoundaryLoop(); + this.hatch.addBoundaryLoop(loop); - // set the flags - this.polylineBoundary = false; - this.parseBoundary = true; + // set the flags + this.polylineBoundary = false; + this.parseBoundary = true; - if ((value.getIntegerValue() & 2) == 2) { - } + if ((value.getIntegerValue() & 2) == 2) {} - if ((value.getIntegerValue() & 1) == 1) { - // from external hatch - } + if ((value.getIntegerValue() & 1) == 1) { + // from external hatch + } - if ((value.getIntegerValue() & 4) == 4) { - // from derivated hatch - } + if ((value.getIntegerValue() & 4) == 4) { + // from derivated hatch + } - if ((value.getIntegerValue() & 16) == 16) { - // different from the DXF-Specs - // if bit is set the loop is not - this.loop.setOutermost(false); - } + if ((value.getIntegerValue() & 16) == 16) { + // different from the DXF-Specs + // if bit is set the loop is not + this.loop.setOutermost(false); + } - break; + break; - case GROUPCODE_NAME: - this.hatch.setName(value.getValue()); + case GROUPCODE_NAME: + this.hatch.setName(value.getValue()); - break; + break; - case GROUPCODE_START_X: + case GROUPCODE_START_X: - if (parseBoundary) { - parseBoundary(groupCode, value); - } else { - this.hatch.getElevationPoint().setX(value.getDoubleValue()); - } + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + this.hatch.getElevationPoint().setX(value.getDoubleValue()); + } - break; + break; - case GROUPCODE_START_Y: + case GROUPCODE_START_Y: - if (parseBoundary) { - parseBoundary(groupCode, value); - } else { - this.hatch.getElevationPoint().setY(value.getDoubleValue()); - } + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + this.hatch.getElevationPoint().setY(value.getDoubleValue()); + } - break; + break; - case GROUPCODE_START_Z: + case GROUPCODE_START_Z: - if (parseBoundary) { - parseBoundary(groupCode, value); - } else { - this.hatch.getElevationPoint().setZ(value.getDoubleValue()); - } + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + this.hatch.getElevationPoint().setZ(value.getDoubleValue()); + } - break; + break; - case GROUPCODE_HATCH_STYLE: - this.parseBoundary = false; - this.endBoundaryElement(); + case GROUPCODE_HATCH_STYLE: + this.parseBoundary = false; + this.endBoundaryElement(); - // This should be the end of a boundary entity - break; + // This should be the end of a boundary entity + break; - case GROUPCODE_PATTERN_LINE_ANGLE: - // set the previus parsed line data - this.parseBoundary = false; - this.linePattern = new HatchLineFamily(); - this.pattern.addLineFamily(this.linePattern); + case GROUPCODE_PATTERN_LINE_ANGLE: + // set the previus parsed line data + this.parseBoundary = false; + this.linePattern = new HatchLineFamily(); + this.pattern.addLineFamily(this.linePattern); - this.linePattern.setRotationAngle(value.getDoubleValue()); - this.count = 0; + this.linePattern.setRotationAngle(value.getDoubleValue()); + this.count = 0; - break; + break; - case GROUPCODE_PATTERN_BASE_X: - this.linePattern.setBaseX(value.getDoubleValue()); + case GROUPCODE_PATTERN_BASE_X: + this.linePattern.setBaseX(value.getDoubleValue()); - break; + break; - case GROUPCODE_PATTERN_BASE_Y: - this.linePattern.setBaseY(value.getDoubleValue()); + case GROUPCODE_PATTERN_BASE_Y: + this.linePattern.setBaseY(value.getDoubleValue()); - break; + break; - case GROUPCODE_PATTERN_OFFSET_X: - this.linePattern.setOffsetX(value.getDoubleValue()); + case GROUPCODE_PATTERN_OFFSET_X: + this.linePattern.setOffsetX(value.getDoubleValue()); - break; + break; - case GROUPCODE_PATTERN_OFFSET_Y: - this.linePattern.setOffsetY(value.getDoubleValue()); + case GROUPCODE_PATTERN_OFFSET_Y: + this.linePattern.setOffsetY(value.getDoubleValue()); - break; + break; - case GROUPCODE_PATTERN_LINE_COUNT: - this.parameters = new double[value.getIntegerValue()]; - this.linePattern.setPattern(this.parameters); + case GROUPCODE_PATTERN_LINE_COUNT: + this.parameters = new double[value.getIntegerValue()]; + this.linePattern.setPattern(this.parameters); - break; + break; - case GROUPCODE_PATTERN_LINE_TYPE_DATA: - this.parameters[this.count] = value.getDoubleValue(); - this.count++; + case GROUPCODE_PATTERN_LINE_TYPE_DATA: + this.parameters[this.count] = value.getDoubleValue(); + this.count++; - break; + break; - case GROUPCODE_PATTERN_SCALE: - this.hatch.setPatternScale(value.getDoubleValue()); + case GROUPCODE_PATTERN_SCALE: + this.hatch.setPatternScale(value.getDoubleValue()); - break; + break; - default: + default: - if (parseBoundary) { - parseBoundary(groupCode, value); - } else { - super.parseCommonProperty(groupCode, value, this.hatch); - } - } + if (parseBoundary) { + parseBoundary(groupCode, value); + } else { + super.parseCommonProperty(groupCode, value, this.hatch); + } + } - this.lastGroupCode = groupCode; - } + this.lastGroupCode = groupCode; + } - protected void parsePolylineBoundary(int groupCode, DXFValue value) { - switch (groupCode) { - case GROUPCODE_START_X: - this.vertex = new DXFVertex(); - this.polyline.addVertex(vertex); - this.vertex.setX(value.getDoubleValue()); + /** + * Parses the polyline boundary. + * + * @param groupCode + * the group code + * @param value + * the value + */ + protected void parsePolylineBoundary(final int groupCode, final DXFValue value) { + switch (groupCode) { + case GROUPCODE_START_X: + this.vertex = new DXFVertex(); + this.polyline.addVertex(vertex); + this.vertex.setX(value.getDoubleValue()); - break; + break; - case GROUPCODE_START_Y: - this.vertex.setY(value.getDoubleValue()); + case GROUPCODE_START_Y: + this.vertex.setY(value.getDoubleValue()); - break; + break; - case GROUPCODE_START_Z: - this.vertex.setZ(value.getDoubleValue()); + case GROUPCODE_START_Z: + this.vertex.setZ(value.getDoubleValue()); - break; + break; - case DXFPolylineHandler.VERTEX_BULGE: - this.vertex.setBulge(value.getDoubleValue()); + case DXFPolylineHandler.VERTEX_BULGE: + this.vertex.setBulge(value.getDoubleValue()); - break; + break; - case 73: - this.polyline.setFlags(1); + case 73: + this.polyline.setFlags(1); - break; - } - } + break; + } + } - /* - * (non-Javadoc) - * - * @see org.kabeja.parser.Handler#setDXFDocument(org.kabeja.dxf.DXFDocument) - */ - public void setDXFDocument(DXFDocument doc) { - super.setDXFDocument(doc); + /* + * (non-Javadoc) + * + * @see org.kabeja.parser.Handler#setDXFDocument(org.kabeja.dxf.DXFDocument) + */ + @Override + public void setDXFDocument(final DXFDocument doc) { + super.setDXFDocument(doc); - Iterator i = this.boundaryHandlers.values().iterator(); + Iterator i = this.boundaryHandlers.values().iterator(); - while (i.hasNext()) { - DXFEntityHandler handler = (DXFEntityHandler) i.next(); - handler.setDXFDocument(doc); - } - } + while (i.hasNext()) { + DXFEntityHandler handler = (DXFEntityHandler) i.next(); + handler.setDXFDocument(doc); + } + } - /* - * (non-Javadoc) - * - * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() - */ - public void startDXFEntity() { - this.hatch = new DXFHatch(); - this.pattern = new DXFHatchPattern(); + /* + * (non-Javadoc) + * + * @see de.miethxml.kabeja.parser.entities.DXFEntityHandler#startDXFEntity() + */ + @Override + public void startDXFEntity() { + this.hatch = new DXFHatch(); + this.pattern = new DXFHatchPattern(); - this.pattern.setHatch(this.hatch); - this.doc.addDXFHatchPattern(pattern); + this.pattern.setHatch(this.hatch); + this.doc.addDXFHatchPattern(pattern); - // setup the flags - this.parseBoundary = false; - this.polylineBoundary = false; - boundaryHandler = null; - } + // setup the flags + this.parseBoundary = false; + this.polylineBoundary = false; + boundaryHandler = null; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/LayerFilter.java b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/LayerFilter.java index feaebba7d6..8c5960ce30 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/LayerFilter.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/LayerFilter.java @@ -1,18 +1,13 @@ -/* - Copyright 2008 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * LayerFilter.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.processing; import java.util.HashSet; @@ -25,82 +20,89 @@ import msi.gama.ext.kabeja.dxf.DXFEntity; import msi.gama.ext.kabeja.dxf.DXFLayer; - +/** + * The Class LayerFilter. + */ public class LayerFilter extends AbstractPostProcessor { - public final static String PROPERTY_REMOVE_LAYERS = "layers.remove"; - public final static String PROPERTY_MERGE_LAYERS = "layers.merge"; - public final static String MERGED_LAYER_NAME = "ALL"; - protected boolean merge = false; - protected Set removableLayers = new HashSet(); - - public void setProperties(Map properties) { - super.setProperties(properties); - - if (properties.containsKey(PROPERTY_MERGE_LAYERS)) { - this.merge = Boolean.valueOf((String) properties.get( - PROPERTY_MERGE_LAYERS)).booleanValue(); - } - - if (properties.containsKey(PROPERTY_REMOVE_LAYERS)) { - this.removableLayers.clear(); - - StringTokenizer st = new StringTokenizer((String) properties.get( - PROPERTY_REMOVE_LAYERS), "|"); - - while (st.hasMoreTokens()) { - this.removableLayers.add(st.nextToken()); - } - } - } - - public void process(DXFDocument doc, Map context) throws ProcessorException { - DXFLayer mergeLayer = null; - - if (this.merge) { - if (doc.containsDXFLayer(MERGED_LAYER_NAME)) { - mergeLayer = doc.getDXFLayer(MERGED_LAYER_NAME); - } else { - mergeLayer = new DXFLayer(); - mergeLayer.setName(MERGED_LAYER_NAME); - doc.addDXFLayer(mergeLayer); - } - } - - // iterate over all layers - Iterator i = doc.getDXFLayerIterator(); - - while (i.hasNext()) { - DXFLayer layer = (DXFLayer) i.next(); - - if (this.removableLayers.contains(layer.getName())) { - i.remove(); - } else if (this.merge) { - if (layer != mergeLayer) { - Iterator types = layer.getDXFEntityTypeIterator(); - - while (types.hasNext()) { - String type = (String) types.next(); - Iterator entityIterator = layer.getDXFEntities(type) - .iterator(); - - while (entityIterator.hasNext()) { - DXFEntity e = (DXFEntity) entityIterator.next(); - // we set all entities to the merged layer - // and remove them from the last layer - e.setLayerName(MERGED_LAYER_NAME); - - // set again to the doc, which will - // place the entity on the right - // layer -> the LAYER = "ALL" - doc.addDXFEntity(e); - entityIterator.remove(); - } - } - - // remove the layer - i.remove(); - } - } - } - } + + /** The Constant PROPERTY_REMOVE_LAYERS. */ + public final static String PROPERTY_REMOVE_LAYERS = "layers.remove"; + + /** The Constant PROPERTY_MERGE_LAYERS. */ + public final static String PROPERTY_MERGE_LAYERS = "layers.merge"; + + /** The Constant MERGED_LAYER_NAME. */ + public final static String MERGED_LAYER_NAME = "ALL"; + + /** The merge. */ + protected boolean merge = false; + + /** The removable layers. */ + protected Set removableLayers = new HashSet<>(); + + @Override + public void setProperties(final Map properties) { + super.setProperties(properties); + + if (properties.containsKey(PROPERTY_MERGE_LAYERS)) { + this.merge = Boolean.parseBoolean((String) properties.get(PROPERTY_MERGE_LAYERS)); + } + + if (properties.containsKey(PROPERTY_REMOVE_LAYERS)) { + this.removableLayers.clear(); + + StringTokenizer st = new StringTokenizer((String) properties.get(PROPERTY_REMOVE_LAYERS), "|"); + + while (st.hasMoreTokens()) { this.removableLayers.add(st.nextToken()); } + } + } + + @Override + public void process(final DXFDocument doc, final Map context) throws ProcessorException { + DXFLayer mergeLayer = null; + + if (this.merge) { + if (doc.containsDXFLayer(MERGED_LAYER_NAME)) { + mergeLayer = doc.getDXFLayer(MERGED_LAYER_NAME); + } else { + mergeLayer = new DXFLayer(); + mergeLayer.setName(MERGED_LAYER_NAME); + doc.addDXFLayer(mergeLayer); + } + } + + // iterate over all layers + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer layer = (DXFLayer) i.next(); + + if (this.removableLayers.contains(layer.getName())) { + i.remove(); + } else if (this.merge && (layer != mergeLayer)) { + Iterator types = layer.getDXFEntityTypeIterator(); + + while (types.hasNext()) { + String type = (String) types.next(); + Iterator entityIterator = layer.getDXFEntities(type).iterator(); + + while (entityIterator.hasNext()) { + DXFEntity e = (DXFEntity) entityIterator.next(); + // we set all entities to the merged layer + // and remove them from the last layer + e.setLayerName(MERGED_LAYER_NAME); + + // set again to the doc, which will + // place the entity on the right + // layer -> the LAYER = "ALL" + doc.addDXFEntity(e); + entityIterator.remove(); + } + } + + // remove the layer + i.remove(); + } + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PolylineConverter.java b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PolylineConverter.java index 3214316484..ab539fedc2 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PolylineConverter.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PolylineConverter.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * PolylineConverter.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.processing; import java.util.ArrayList; @@ -31,161 +26,185 @@ import msi.gama.ext.kabeja.dxf.helpers.Point; import msi.gama.ext.kabeja.processing.helper.PolylineQueue; - +/** + * The Class PolylineConverter. + */ public class PolylineConverter extends AbstractPostProcessor { - public final static String PROPERTY_POINT_DISTANCE = "point.distance"; - private List queues; - private double radius = DXFConstants.POINT_CONNECTION_RADIUS; - - public void process(DXFDocument doc, Map context) throws ProcessorException { - Iterator i = doc.getDXFLayerIterator(); - - while (i.hasNext()) { - DXFLayer layer = (DXFLayer) i.next(); - - processLayer(layer); - } - - // TODO process the blocks too - } - - public void setProperties(Map properties) { - if (properties.containsKey(PROPERTY_POINT_DISTANCE)) { - this.radius = Double.parseDouble((String) properties.get( - PROPERTY_POINT_DISTANCE)); - } - } - - protected void processLayer(DXFLayer layer) { - this.queues = new ArrayList(); - - // check the lines - if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_LINE)) { - List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LINE); - Iterator i = l.iterator(); - - while (i.hasNext()) { - DXFLine line = (DXFLine) i.next(); - Point start = line.getStartPoint(); - Point end = line.getEndPoint(); - checkDXFEntity(line, start, end); - } - } - - // check the polylines - if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE)) { - List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE); - Iterator i = l.iterator(); - - while (i.hasNext()) { - DXFPolyline pl = (DXFPolyline) i.next(); - - if (!pl.isClosed() && !pl.is3DPolygonMesh() && - !pl.isClosedMeshMDirection() && - !pl.isClosedMeshNDirection() && - !pl.isCubicSurefaceMesh()) { - Point start = pl.getVertex(0).getPoint(); - Point end = pl.getVertex(pl.getVertexCount() - 1).getPoint(); - checkDXFEntity(pl, start, end); - } - } - } - - // check the lwpolylines - if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE)) { - List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE); - Iterator i = l.iterator(); - - while (i.hasNext()) { - DXFLWPolyline pl = (DXFLWPolyline) i.next(); - - if (!pl.isClosed() && !pl.is3DPolygonMesh() && - !pl.isClosedMeshMDirection() && - !pl.isClosedMeshNDirection() && - !pl.isCubicSurefaceMesh()) { - Point start = pl.getVertex(0).getPoint(); - Point end = pl.getVertex(pl.getVertexCount() - 1).getPoint(); - checkDXFEntity(pl, start, end); - } - } - } - - // check the arcs - if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_ARC)) { - List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_ARC); - Iterator i = l.iterator(); - - while (i.hasNext()) { - DXFArc arc = (DXFArc) i.next(); - - // note that this points are calculated - // and could be not connected to the rest - // even though they should in you CAD - Point start = arc.getStartPoint(); - Point end = arc.getEndPoint(); - checkDXFEntity(arc, start, end); - } - } - - // finish up the connection search - // and connect parts, if it is possible - connectPolylineQueues(); - - cleanUp(layer); - } - - protected void checkDXFEntity(DXFEntity e, Point start, Point end) { - Iterator i = this.queues.iterator(); - - while (i.hasNext()) { - PolylineQueue queue = (PolylineQueue) i.next(); - - if (queue.connectDXFEntity(e, start, end)) { - return; - } - } - - // nothing found create a new queue - PolylineQueue queue = new PolylineQueue(e, start, end, this.radius); - - this.queues.add(queue); - } - - protected void cleanUp(DXFLayer layer) { - Iterator i = this.queues.iterator(); - - while (i.hasNext()) { - PolylineQueue queue = (PolylineQueue) i.next(); - - if (queue.size() > 1) { - queue.createDXFPolyline(layer); - } else { - // ignore - i.remove(); - } - } - } - - /** - * Goes through all polylinequeues and connect them, if they have the same - * start and end points. - * - */ - protected void connectPolylineQueues() { - for (int i = 0; i < this.queues.size(); i++) { - PolylineQueue queue = (PolylineQueue) this.queues.get(i); - - boolean connected = false; - - //inner loop -> test all following polylines if - //we can connect - for (int x = i + 1; (x < this.queues.size()) && !connected; x++) { - if (((PolylineQueue) this.queues.get(x)).connect(queue)) { - this.queues.remove(i); - i--; - connected = true; - } - } - } - } + + /** The Constant PROPERTY_POINT_DISTANCE. */ + public final static String PROPERTY_POINT_DISTANCE = "point.distance"; + + /** The queues. */ + private List queues; + + /** The radius. */ + private double radius = DXFConstants.POINT_CONNECTION_RADIUS; + + @Override + public void process(final DXFDocument doc, final Map context) throws ProcessorException { + Iterator i = doc.getDXFLayerIterator(); + + while (i.hasNext()) { + DXFLayer layer = (DXFLayer) i.next(); + + processLayer(layer); + } + + // TODO process the blocks too + } + + @Override + public void setProperties(final Map properties) { + if (properties.containsKey(PROPERTY_POINT_DISTANCE)) { + this.radius = Double.parseDouble((String) properties.get(PROPERTY_POINT_DISTANCE)); + } + } + + /** + * Process layer. + * + * @param layer + * the layer + */ + protected void processLayer(final DXFLayer layer) { + this.queues = new ArrayList<>(); + + // check the lines + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_LINE)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LINE); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFLine line = (DXFLine) i.next(); + Point start = line.getStartPoint(); + Point end = line.getEndPoint(); + checkDXFEntity(line, start, end); + } + } + + // check the polylines + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_POLYLINE); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFPolyline pl = (DXFPolyline) i.next(); + + if (!pl.isClosed() && !pl.is3DPolygonMesh() && !pl.isClosedMeshMDirection() + && !pl.isClosedMeshNDirection() && !pl.isCubicSurefaceMesh()) { + Point start = pl.getVertex(0).getPoint(); + Point end = pl.getVertex(pl.getVertexCount() - 1).getPoint(); + checkDXFEntity(pl, start, end); + } + } + } + + // check the lwpolylines + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_LWPOLYLINE); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFLWPolyline pl = (DXFLWPolyline) i.next(); + + if (!pl.isClosed() && !pl.is3DPolygonMesh() && !pl.isClosedMeshMDirection() + && !pl.isClosedMeshNDirection() && !pl.isCubicSurefaceMesh()) { + Point start = pl.getVertex(0).getPoint(); + Point end = pl.getVertex(pl.getVertexCount() - 1).getPoint(); + checkDXFEntity(pl, start, end); + } + } + } + + // check the arcs + if (layer.hasDXFEntities(DXFConstants.ENTITY_TYPE_ARC)) { + List l = layer.getDXFEntities(DXFConstants.ENTITY_TYPE_ARC); + Iterator i = l.iterator(); + + while (i.hasNext()) { + DXFArc arc = (DXFArc) i.next(); + + // note that this points are calculated + // and could be not connected to the rest + // even though they should in you CAD + Point start = arc.getStartPoint(); + Point end = arc.getEndPoint(); + checkDXFEntity(arc, start, end); + } + } + + // finish up the connection search + // and connect parts, if it is possible + connectPolylineQueues(); + + cleanUp(layer); + } + + /** + * Check DXF entity. + * + * @param e + * the e + * @param start + * the start + * @param end + * the end + */ + protected void checkDXFEntity(final DXFEntity e, final Point start, final Point end) { + Iterator i = this.queues.iterator(); + + while (i.hasNext()) { + PolylineQueue queue = (PolylineQueue) i.next(); + + if (queue.connectDXFEntity(e, start, end)) return; + } + + // nothing found create a new queue + PolylineQueue queue = new PolylineQueue(e, start, end, this.radius); + + this.queues.add(queue); + } + + /** + * Clean up. + * + * @param layer + * the layer + */ + protected void cleanUp(final DXFLayer layer) { + Iterator i = this.queues.iterator(); + + while (i.hasNext()) { + PolylineQueue queue = (PolylineQueue) i.next(); + + if (queue.size() > 1) { + queue.createDXFPolyline(layer); + } else { + // ignore + i.remove(); + } + } + } + + /** + * Goes through all polylinequeues and connect them, if they have the same start and end points. + * + */ + protected void connectPolylineQueues() { + for (int i = 0; i < this.queues.size(); i++) { + PolylineQueue queue = this.queues.get(i); + + boolean connected = false; + + // inner loop -> test all following polylines if + // we can connect + for (int x = i + 1; x < this.queues.size() && !connected; x++) { + if (this.queues.get(x).connect(queue)) { + this.queues.remove(i); + i--; + connected = true; + } + } + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessManager.java b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessManager.java index a3044e1b40..3fe724ef5e 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessManager.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessManager.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * PostProcessManager.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.processing; import java.util.ArrayList; @@ -21,42 +16,57 @@ import msi.gama.ext.kabeja.dxf.DXFDocument; - /** * @author Simon Mieth * */ public class PostProcessManager { - private ArrayList processors = new ArrayList(); - - public void addPostProcessor(PostProcessor pp) { - processors.add(pp); - } - - public void addPostProcessor(String classname) { - try { - PostProcessor pp = (PostProcessor) this.getClass().getClassLoader() - .loadClass(classname) - .newInstance(); - addPostProcessor(pp); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void process(DXFDocument doc, Map context) throws ProcessorException { - Iterator i = processors.iterator(); - - while (i.hasNext()) { - PostProcessor pp = (PostProcessor) i.next(); - pp.process(doc, context); - } - } + + /** The processors. */ + private final ArrayList processors = new ArrayList<>(); + + /** + * Adds the post processor. + * + * @param pp + * the pp + */ + public void addPostProcessor(final PostProcessor pp) { + processors.add(pp); + } + + /** + * Adds the post processor. + * + * @param classname + * the classname + */ + public void addPostProcessor(final String classname) { + try { + PostProcessor pp = (PostProcessor) this.getClass().getClassLoader().loadClass(classname).newInstance(); + addPostProcessor(pp); + } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + /** + * Process. + * + * @param doc + * the doc + * @param context + * the context + * @throws ProcessorException + * the processor exception + */ + public void process(final DXFDocument doc, final Map context) throws ProcessorException { + Iterator i = processors.iterator(); + + while (i.hasNext()) { + PostProcessor pp = (PostProcessor) i.next(); + pp.process(doc, context); + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessorConfig.java b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessorConfig.java index 4d5a08ee02..69d566d3fb 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessorConfig.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/PostProcessorConfig.java @@ -1,59 +1,74 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * PostProcessorConfig.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.processing; import java.util.HashMap; import java.util.Map; - /** * @author Simon Mieth * */ public class PostProcessorConfig { - private Map properties = new HashMap(); - private String postProcessorName; - - public PostProcessorConfig(Map properties) { - this.properties = properties; - } - - public PostProcessorConfig() { - this(new HashMap()); - } - - public Map getProperties() { - return this.properties; - } - - public void addProperty(String name, String value) { - this.properties.put(name, value); - } - - /** - * @return Returns the filterName. - */ - public String getPostProcessorName() { - return postProcessorName; - } - - /** - * @param filterName The filterName to set. - */ - public void setPostProcessorName(String filterName) { - this.postProcessorName = filterName; - } + + /** The properties. */ + private Map properties = new HashMap<>(); + + /** The post processor name. */ + private String postProcessorName; + + /** + * Instantiates a new post processor config. + * + * @param properties + * the properties + */ + public PostProcessorConfig(final Map properties) { + this.properties = properties; + } + + /** + * Instantiates a new post processor config. + */ + public PostProcessorConfig() { + this(new HashMap<>()); + } + + /** + * Gets the properties. + * + * @return the properties + */ + public Map getProperties() { return this.properties; } + + /** + * Adds the property. + * + * @param name + * the name + * @param value + * the value + */ + public void addProperty(final String name, final String value) { + this.properties.put(name, value); + } + + /** + * @return Returns the filterName. + */ + public String getPostProcessorName() { return postProcessorName; } + + /** + * @param filterName + * The filterName to set. + */ + public void setPostProcessorName(final String filterName) { this.postProcessorName = filterName; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessPipeline.java b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessPipeline.java index 2d969e8605..5c1a502d96 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessPipeline.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessPipeline.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * ProcessPipeline.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.processing; import java.io.OutputStream; @@ -22,32 +17,62 @@ import java.util.List; import java.util.Map; +import org.xml.sax.ContentHandler; +import org.xml.sax.SAXException; + import msi.gama.ext.kabeja.dxf.DXFDocument; import msi.gama.ext.kabeja.processing.helper.MergeMap; import msi.gama.ext.kabeja.tools.SAXFilterConfig; import msi.gama.ext.kabeja.xml.SAXFilter; import msi.gama.ext.kabeja.xml.SAXGenerator; import msi.gama.ext.kabeja.xml.SAXSerializer; -import org.xml.sax.ContentHandler; -import org.xml.sax.SAXException; /** * @author Simon Mieth - * + * */ public class ProcessPipeline { + + /** The manager. */ private ProcessingManager manager; - private List postProcessorConfigs = new ArrayList(); - private List saxFilterConfigs = new ArrayList(); + + /** The post processor configs. */ + private final List postProcessorConfigs = new ArrayList<>(); + + /** The sax filter configs. */ + private final List saxFilterConfigs = new ArrayList<>(); + + /** The generator. */ private SAXGenerator generator; + + /** The serializer properties. */ private Map serializerProperties = new HashMap(); + + /** The generator properties. */ private Map generatorProperties = new HashMap(); + + /** The serializer. */ private SAXSerializer serializer; + + /** The name. */ private String name; + + /** The description. */ private String description = ""; - public void process(DXFDocument doc, Map context, OutputStream out) - throws ProcessorException { + /** + * Process. + * + * @param doc + * the doc + * @param context + * the context + * @param out + * the out + * @throws ProcessorException + * the processor exception + */ + public void process(final DXFDocument doc, final Map context, final OutputStream out) throws ProcessorException { ContentHandler handler = null; // postprocess @@ -55,8 +80,7 @@ public void process(DXFDocument doc, Map context, OutputStream out) while (i.hasNext()) { PostProcessorConfig ppc = (PostProcessorConfig) i.next(); - PostProcessor pp = this.manager.getPostProcessor(ppc - .getPostProcessorName()); + PostProcessor pp = this.manager.getPostProcessor(ppc.getPostProcessorName()); // backup the default props Map oldProps = pp.getProperties(); @@ -67,20 +91,19 @@ public void process(DXFDocument doc, Map context, OutputStream out) pp.setProperties(oldProps); } - List saxFilterProperties = new ArrayList(); + List saxFilterProperties = new ArrayList<>(); // setup saxfilters if (this.saxFilterConfigs.size() > 0) { i = saxFilterConfigs.iterator(); SAXFilterConfig sc = (SAXFilterConfig) i.next(); SAXFilter first = this.manager.getSAXFilter(sc.getFilterName()); - saxFilterProperties - .add(new MergeMap(first.getProperties(), context)); + saxFilterProperties.add(new MergeMap(first.getProperties(), context)); first.setContentHandler(this.serializer); handler = first; first.setProperties(sc.getProperties()); - + while (i.hasNext()) { sc = (SAXFilterConfig) i.next(); SAXFilter f = this.manager.getSAXFilter(sc.getFilterName()); @@ -88,7 +111,7 @@ public void process(DXFDocument doc, Map context, OutputStream out) saxFilterProperties.add(f.getProperties()); f.setProperties(sc.getProperties()); first = f; - + } } else { @@ -97,8 +120,7 @@ public void process(DXFDocument doc, Map context, OutputStream out) } Map oldProbs = this.serializer.getProperties(); - this.serializer.setProperties(new MergeMap(this.serializerProperties, - context)); + this.serializer.setProperties(new MergeMap(this.serializerProperties, context)); // invoke the filter and serializer this.serializer.setOutput(out); @@ -118,108 +140,137 @@ public void process(DXFDocument doc, Map context, OutputStream out) // restore the filter properties for (int x = 0; x < saxFilterProperties.size(); x++) { - SAXFilterConfig sc = (SAXFilterConfig) saxFilterConfigs.get(x); - this.manager.getSAXFilter(sc.getFilterName()).setProperties( - (Map) saxFilterProperties.get(x)); + SAXFilterConfig sc = saxFilterConfigs.get(x); + this.manager.getSAXFilter(sc.getFilterName()).setProperties(saxFilterProperties.get(x)); } } /** * @return Returns the serializer. */ - public SAXSerializer getSAXSerializer() { - return serializer; - } + public SAXSerializer getSAXSerializer() { return serializer; } /** * @param serializer * The serializer to set. */ - public void setSAXSerializer(SAXSerializer serializer) { - this.serializer = serializer; - } + public void setSAXSerializer(final SAXSerializer serializer) { this.serializer = serializer; } /** * @return Returns the manager. */ - public ProcessingManager getProcessorManager() { - return manager; - } + public ProcessingManager getProcessorManager() { return manager; } /** * @param manager * The manager to set. */ - public void setProcessorManager(ProcessingManager manager) { - this.manager = manager; - } + public void setProcessorManager(final ProcessingManager manager) { this.manager = manager; } /** * @return Returns the name. */ - public String getName() { - return name; - } + public String getName() { return name; } /** * @param name * The name to set. */ - public void setName(String name) { - this.name = name; - } + public void setName(final String name) { this.name = name; } - public void prepare() { - } + /** + * Prepare. + */ + public void prepare() {} - public List getPostProcessorConfigs() { - return this.postProcessorConfigs; - } + /** + * Gets the post processor configs. + * + * @return the post processor configs + */ + public List getPostProcessorConfigs() { return this.postProcessorConfigs; } - public void addSAXFilterConfig(SAXFilterConfig config) { + /** + * Adds the SAX filter config. + * + * @param config + * the config + */ + public void addSAXFilterConfig(final SAXFilterConfig config) { this.saxFilterConfigs.add(config); } - public void addPostProcessorConfig(PostProcessorConfig config) { + /** + * Adds the post processor config. + * + * @param config + * the config + */ + public void addPostProcessorConfig(final PostProcessorConfig config) { this.postProcessorConfigs.add(config); } /** * @return Returns the serializerProperties. */ - public Map getSerializerProperties() { - return serializerProperties; - } + public Map getSerializerProperties() { return serializerProperties; } /** * @param serializerProperties * The serializerProperties to set. */ - public void setSAXSerializerProperties(Map serializerProperties) { + public void setSAXSerializerProperties(final Map serializerProperties) { this.serializerProperties = serializerProperties; } - public void setSAXGeneratorProperties(Map generatorProperties) { + /** + * Sets the SAX generator properties. + * + * @param generatorProperties + * the new SAX generator properties + */ + public void setSAXGeneratorProperties(final Map generatorProperties) { this.generatorProperties = generatorProperties; } - public Map getSAXGeneratorProperties(Map generatorProperties) { + /** + * Gets the SAX generator properties. + * + * @param generatorProperties + * the generator properties + * @return the SAX generator properties + */ + public Map getSAXGeneratorProperties(final Map generatorProperties) { return this.generatorProperties; } - public void setSAXGenerator(SAXGenerator generator) { - this.generator = generator; - } + /** + * Sets the SAX generator. + * + * @param generator + * the new SAX generator + */ + public void setSAXGenerator(final SAXGenerator generator) { this.generator = generator; } - public SAXGenerator getSAXGenerator() { - return this.generator; - } + /** + * Gets the SAX generator. + * + * @return the SAX generator + */ + public SAXGenerator getSAXGenerator() { return this.generator; } - public String getDescription() { - return this.description; - } + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { return this.description; } - public void setDescription(String description) { - this.description = description; - } + /** + * Sets the description. + * + * @param description + * the new description + */ + public void setDescription(final String description) { this.description = description; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessingManager.java b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessingManager.java index cf349238a1..f63a0cb1cb 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessingManager.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/ProcessingManager.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * ProcessingManager.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.processing; import java.io.FileNotFoundException; @@ -33,152 +28,312 @@ import msi.gama.ext.kabeja.xml.SAXGenerator; import msi.gama.ext.kabeja.xml.SAXSerializer; - /** * @author Simon Mieth * */ public class ProcessingManager { - private Map saxfilters = new HashMap(); - private Map saxserializers = new HashMap(); - private Map postprocessors = new HashMap(); - private Map pipelines = new HashMap(); - private Map saxgenerators = new HashMap(); - private List parsers = new ArrayList(); - - public void addSAXFilter(SAXFilter filter, String name) { - this.saxfilters.put(name, filter); - } - - public SAXFilter getSAXFilter(String name) { - return (SAXFilter) this.saxfilters.get(name); - } - - public Map getSAXFilters() { - return this.saxfilters; - } - - public void addSAXSerializer(SAXSerializer serializer, String name) { - this.saxserializers.put(name, serializer); - } - - public SAXSerializer getSAXSerializer(String name) { - return (SAXSerializer) this.saxserializers.get(name); - } - - public Map getSAXSerializers() { - return this.saxserializers; - } - - public void addPostProcessor(PostProcessor pp, String name) { - this.postprocessors.put(name, pp); - } - - public void addParser(Parser parser) { - this.parsers.add(parser); - } - - public List getParsers() { - return this.parsers; - } - - protected Parser getParser(String extension) { - Iterator i = this.parsers.iterator(); - - while (i.hasNext()) { - Parser parser = (Parser) i.next(); - - if (parser.supportedExtension(extension)) { - return parser; - } - } - - return null; - } - - public PostProcessor getPostProcessor(String name) { - return (PostProcessor) this.postprocessors.get(name); - } - - public Map getPostProcessors() { - return this.postprocessors; - } - - public void addProcessPipeline(ProcessPipeline pp) { - pp.setProcessorManager(this); - this.pipelines.put(pp.getName(), pp); - } - - public ProcessPipeline getProcessPipeline(String name) { - return (ProcessPipeline) this.pipelines.get(name); - } - - public Map getProcessPipelines() { - return this.pipelines; - } - - public void process(InputStream stream, String extension, Map context, - String pipeline, OutputStream out) throws ProcessorException { - Parser parser = this.getParser(extension); - - if (parser != null) { - try { - parser.parse(stream, null); - - DXFDocument doc = parser.getDocument(); - this.process(doc, context, pipeline, out); - } catch (ParseException e) { - throw new ProcessorException(e); - } - } - } - - public void process(DXFDocument doc, Map context, String pipeline, - OutputStream out) throws ProcessorException { - if (this.pipelines.containsKey(pipeline)) { - ProcessPipeline pp = (ProcessPipeline) this.pipelines.get(pipeline); - pp.prepare(); - pp.process(doc, context, out); - } else { - throw new ProcessorException("No pipeline found for name:" + - pipeline); - } - } - - public void process(DXFDocument doc, Map context, String pipeline, - String sourceFile) throws ProcessorException { - if (this.pipelines.containsKey(pipeline)) { - try { - ProcessPipeline pp = (ProcessPipeline) this.pipelines.get(pipeline); - String suffix = pp.getSAXSerializer().getSuffix(); - String file = sourceFile.substring(0, - sourceFile.lastIndexOf('.') + 1) + suffix; - FileOutputStream out = new FileOutputStream(file); - process(doc, context, pipeline, out); - } catch (FileNotFoundException e) { - throw new ProcessorException(e); - } - } else { - throw new ProcessorException("No pipeline found for name:" + - pipeline); - } - } - - public void addSAXGenerator(SAXGenerator saxgenerator, String name) { - this.saxgenerators.put(name, saxgenerator); - } - - public SAXGenerator getSAXGenerator(String name) { - return (SAXGenerator) this.saxgenerators.get(name); - } - - public Map getSAXGenerators() { - return this.saxgenerators; - } - - public void addProcessingListener(ProcessingListener l) { - } - - public void removeProcessingListener(ProcessingListener l) { - } + + /** The saxfilters. */ + private final Map saxfilters = new HashMap<>(); + + /** The saxserializers. */ + private final Map saxserializers = new HashMap<>(); + + /** The postprocessors. */ + private final Map postprocessors = new HashMap<>(); + + /** The pipelines. */ + private final Map pipelines = new HashMap<>(); + + /** The saxgenerators. */ + private final Map saxgenerators = new HashMap<>(); + + /** The parsers. */ + private final List parsers = new ArrayList<>(); + + /** + * Adds the SAX filter. + * + * @param filter + * the filter + * @param name + * the name + */ + public void addSAXFilter(final SAXFilter filter, final String name) { + this.saxfilters.put(name, filter); + } + + /** + * Gets the SAX filter. + * + * @param name + * the name + * @return the SAX filter + */ + public SAXFilter getSAXFilter(final String name) { + return this.saxfilters.get(name); + } + + /** + * Gets the SAX filters. + * + * @return the SAX filters + */ + public Map getSAXFilters() { return this.saxfilters; } + + /** + * Adds the SAX serializer. + * + * @param serializer + * the serializer + * @param name + * the name + */ + public void addSAXSerializer(final SAXSerializer serializer, final String name) { + this.saxserializers.put(name, serializer); + } + + /** + * Gets the SAX serializer. + * + * @param name + * the name + * @return the SAX serializer + */ + public SAXSerializer getSAXSerializer(final String name) { + return this.saxserializers.get(name); + } + + /** + * Gets the SAX serializers. + * + * @return the SAX serializers + */ + public Map getSAXSerializers() { return this.saxserializers; } + + /** + * Adds the post processor. + * + * @param pp + * the pp + * @param name + * the name + */ + public void addPostProcessor(final PostProcessor pp, final String name) { + this.postprocessors.put(name, pp); + } + + /** + * Adds the parser. + * + * @param parser + * the parser + */ + public void addParser(final Parser parser) { + this.parsers.add(parser); + } + + /** + * Gets the parsers. + * + * @return the parsers + */ + public List getParsers() { return this.parsers; } + + /** + * Gets the parser. + * + * @param extension + * the extension + * @return the parser + */ + protected Parser getParser(final String extension) { + Iterator i = this.parsers.iterator(); + + while (i.hasNext()) { + Parser parser = (Parser) i.next(); + + if (parser.supportedExtension(extension)) return parser; + } + + return null; + } + + /** + * Gets the post processor. + * + * @param name + * the name + * @return the post processor + */ + public PostProcessor getPostProcessor(final String name) { + return this.postprocessors.get(name); + } + + /** + * Gets the post processors. + * + * @return the post processors + */ + public Map getPostProcessors() { return this.postprocessors; } + + /** + * Adds the process pipeline. + * + * @param pp + * the pp + */ + public void addProcessPipeline(final ProcessPipeline pp) { + pp.setProcessorManager(this); + this.pipelines.put(pp.getName(), pp); + } + + /** + * Gets the process pipeline. + * + * @param name + * the name + * @return the process pipeline + */ + public ProcessPipeline getProcessPipeline(final String name) { + return this.pipelines.get(name); + } + + /** + * Gets the process pipelines. + * + * @return the process pipelines + */ + public Map getProcessPipelines() { return this.pipelines; } + + /** + * Process. + * + * @param stream + * the stream + * @param extension + * the extension + * @param context + * the context + * @param pipeline + * the pipeline + * @param out + * the out + * @throws ProcessorException + * the processor exception + */ + public void process(final InputStream stream, final String extension, final Map context, final String pipeline, + final OutputStream out) throws ProcessorException { + Parser parser = this.getParser(extension); + + if (parser != null) { + try { + parser.parse(stream, null); + + DXFDocument doc = parser.getDocument(); + this.process(doc, context, pipeline, out); + } catch (ParseException e) { + throw new ProcessorException(e); + } + } + } + + /** + * Process. + * + * @param doc + * the doc + * @param context + * the context + * @param pipeline + * the pipeline + * @param out + * the out + * @throws ProcessorException + * the processor exception + */ + public void process(final DXFDocument doc, final Map context, final String pipeline, final OutputStream out) + throws ProcessorException { + if (!this.pipelines.containsKey(pipeline)) + throw new ProcessorException("No pipeline found for name:" + pipeline); + ProcessPipeline pp = this.pipelines.get(pipeline); + pp.prepare(); + pp.process(doc, context, out); + } + + /** + * Process. + * + * @param doc + * the doc + * @param context + * the context + * @param pipeline + * the pipeline + * @param sourceFile + * the source file + * @throws ProcessorException + * the processor exception + */ + public void process(final DXFDocument doc, final Map context, final String pipeline, final String sourceFile) + throws ProcessorException { + if (!this.pipelines.containsKey(pipeline)) + throw new ProcessorException("No pipeline found for name:" + pipeline); + try { + ProcessPipeline pp = this.pipelines.get(pipeline); + String suffix = pp.getSAXSerializer().getSuffix(); + String file = sourceFile.substring(0, sourceFile.lastIndexOf('.') + 1) + suffix; + FileOutputStream out = new FileOutputStream(file); + process(doc, context, pipeline, out); + } catch (FileNotFoundException e) { + throw new ProcessorException(e); + } + } + + /** + * Adds the SAX generator. + * + * @param saxgenerator + * the saxgenerator + * @param name + * the name + */ + public void addSAXGenerator(final SAXGenerator saxgenerator, final String name) { + this.saxgenerators.put(name, saxgenerator); + } + + /** + * Gets the SAX generator. + * + * @param name + * the name + * @return the SAX generator + */ + public SAXGenerator getSAXGenerator(final String name) { + return this.saxgenerators.get(name); + } + + /** + * Gets the SAX generators. + * + * @return the SAX generators + */ + public Map getSAXGenerators() { return this.saxgenerators; } + + /** + * Adds the processing listener. + * + * @param l + * the l + */ + public void addProcessingListener(final ProcessingListener l) {} + + /** + * Removes the processing listener. + * + * @param l + * the l + */ + public void removeProcessingListener(final ProcessingListener l) {} } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/helper/PolylineQueue.java b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/helper/PolylineQueue.java index 2ab4834ed7..934eca737f 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/processing/helper/PolylineQueue.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/processing/helper/PolylineQueue.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * PolylineQueue.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.processing.helper; import java.util.ArrayList; @@ -29,228 +24,284 @@ import msi.gama.ext.kabeja.dxf.helpers.DXFUtils; import msi.gama.ext.kabeja.dxf.helpers.Point; - +/** + * The Class PolylineQueue. + */ public class PolylineQueue { - private List elements = new ArrayList(); - private Point startPoint; - private Point endPoint; - private double radius = DXFConstants.POINT_CONNECTION_RADIUS; - - public PolylineQueue(DXFEntity e, Point start, Point end, double radius) { - this.elements.add(e); - this.startPoint = start; - this.endPoint = end; - this.radius = radius; - } - - public int size() { - return this.elements.size(); - } - - /** - * connect a DXF entity if possible. - * - * @param e - * @param start - * @param end - * @return true if the entity could be connected, otherwise false - */ - public boolean connectDXFEntity(DXFEntity e, Point start, Point end) { - if (DXFUtils.equals(this.startPoint, end, radius)) { - this.startPoint = start; - this.elements.add(0, e); - - return true; - } else if (DXFUtils.equals(this.endPoint, start, radius)) { - this.endPoint = end; - this.elements.add(e); - - return true; - } else if (DXFUtils.equals(this.startPoint, start, radius)) { - // we need to reverse then the entity - this.startPoint = end; - reverse(e); - this.elements.add(0, e); - - return true; - } else if (DXFUtils.equals(this.endPoint, end, radius)) { - // we need to reverse then the entity - this.endPoint = start; - reverse(e); - this.elements.add(e); - - return true; - } - - return false; - } - - public Point getStartPoint() { - return this.startPoint; - } - - public Point getEndPoint() { - return this.endPoint; - } - - public Iterator getElementIterator() { - return this.elements.iterator(); - } - - public boolean connect(PolylineQueue queue) { - if (DXFUtils.equals(queue.getStartPoint(), this.endPoint, radius)) { - // add to the end - add(queue); - - return true; - } else if (DXFUtils.equals(queue.getEndPoint(), this.startPoint, radius)) { - // insert before - insertBefore(queue); - - return true; - } else if (DXFUtils.equals(queue.getStartPoint(), this.startPoint, - radius)) { - queue.reverse(); - insertBefore(queue); - - return true; - } else if (DXFUtils.equals(queue.getEndPoint(), this.endPoint, radius)) { - queue.reverse(); - add(queue); - - return true; - } - - return false; - } - - public void createDXFPolyline(DXFLayer layer) { - // create the polyline and remove the entity - DXFPolyline pline = new DXFPolyline(); - DXFVertex first = new DXFVertex(this.startPoint); - pline.addVertex(first); - - Iterator i = this.elements.iterator(); - - while (i.hasNext()) { - DXFEntity e = (DXFEntity) i.next(); - - if (DXFConstants.ENTITY_TYPE_LINE.equals(e.getType())) { - DXFLine line = (DXFLine) e; - first = new DXFVertex(line.getEndPoint()); - pline.addVertex(first); - } else if (DXFConstants.ENTITY_TYPE_POLYLINE.equals(e.getType()) || - DXFConstants.ENTITY_TYPE_LWPOLYLINE.equals(e.getType())) { - DXFPolyline pl = (DXFPolyline) e; - double bulge = pl.getVertex(0).getBulge(); - - if (bulge != 0.0) { - first.setBulge(bulge); - } - - for (int x = 1; x < pl.getVertexCount(); x++) { - first = pl.getVertex(x); - pline.addVertex(first); - } - } else if (DXFConstants.ENTITY_TYPE_ARC.equals(e.getType())) { - DXFArc arc = (DXFArc) e; - - if (arc.getTotalAngle() > 0.0) { - double h = arc.getRadius() * (1 - - Math.cos(Math.toRadians(arc.getTotalAngle() / 2))); - double chordLength = arc.getChordLength(); - - if (DXFUtils.equals(arc.getStartPoint(), first.getPoint(), - radius)) { - // the last point is our start point, - // which is always set - // we have to calculate the bulge - first.setBulge((2 * h) / chordLength); - first = new DXFVertex(arc.getEndPoint()); - pline.addVertex(first); - } else { - // reverse the arc, we change the start/end points - // and set the bulge to >0 - first.setBulge(-1.0 * ((2 * h) / chordLength)); - - first = new DXFVertex(arc.getStartPoint()); - pline.addVertex(first); - } - } - } - - // remove from layer - layer.removeDXFEntity(e); - } - - // add the new polyline to the layer - pline.setLayerName(layer.getName()); - layer.addDXFEntity(pline); - } - - protected void reverse(DXFEntity entity) { - if (DXFConstants.ENTITY_TYPE_LINE.equals(entity.getType())) { - DXFUtils.reverseDXFLine((DXFLine) entity); - } else if (DXFConstants.ENTITY_TYPE_POLYLINE.equals(entity.getType()) || - DXFConstants.ENTITY_TYPE_LWPOLYLINE.equals(entity.getType())) { - DXFUtils.reverseDXFPolyline((DXFPolyline) entity); - } else if (DXFConstants.ENTITY_TYPE_ARC.equals(entity.getType())) { - // we cannot reverse a DXF ARC - } - } - - protected void reverse() { - Point p = this.endPoint; - this.endPoint = this.startPoint; - this.startPoint = p; - - // reverse the list and all entities - int last = this.elements.size() - 1; - - for (int i = 0; i < (last + 1); i++) { - DXFEntity first = (DXFEntity) this.elements.get(i); - this.reverse(first); - - if (i < last) { - DXFEntity e = (DXFEntity) this.elements.set(last, first); - this.reverse(e); - this.elements.set(i, e); - last--; - } - } - } - - /** - * Insert the PolylineQueue before the first element. - * - * @param queue - */ - public void insertBefore(PolylineQueue queue) { - this.startPoint = queue.getStartPoint(); - - Iterator i = queue.getElementIterator(); - int x = 0; - - while (i.hasNext()) { - DXFEntity e = (DXFEntity) i.next(); - this.elements.add(x, e); - x++; - } - } - - /** - * Adds the queue to the end. - * - * @param queue - */ - public void add(PolylineQueue queue) { - this.endPoint = queue.getEndPoint(); - - Iterator i = queue.getElementIterator(); - - while (i.hasNext()) { - DXFEntity e = (DXFEntity) i.next(); - this.elements.add(e); - } - } + + /** The elements. */ + private final List elements = new ArrayList<>(); + + /** The start point. */ + private Point startPoint; + + /** The end point. */ + private Point endPoint; + + /** The radius. */ + private double radius = DXFConstants.POINT_CONNECTION_RADIUS; + + /** + * Instantiates a new polyline queue. + * + * @param e + * the e + * @param start + * the start + * @param end + * the end + * @param radius + * the radius + */ + public PolylineQueue(final DXFEntity e, final Point start, final Point end, final double radius) { + this.elements.add(e); + this.startPoint = start; + this.endPoint = end; + this.radius = radius; + } + + /** + * Size. + * + * @return the int + */ + public int size() { + return this.elements.size(); + } + + /** + * connect a DXF entity if possible. + * + * @param e + * @param start + * @param end + * @return true if the entity could be connected, otherwise false + */ + public boolean connectDXFEntity(final DXFEntity e, final Point start, final Point end) { + if (DXFUtils.equals(this.startPoint, end, radius)) { + this.startPoint = start; + this.elements.add(0, e); + + return true; + } + if (DXFUtils.equals(this.endPoint, start, radius)) { + this.endPoint = end; + this.elements.add(e); + + return true; + } + if (DXFUtils.equals(this.startPoint, start, radius)) { + // we need to reverse then the entity + this.startPoint = end; + reverse(e); + this.elements.add(0, e); + + return true; + } else if (DXFUtils.equals(this.endPoint, end, radius)) { + // we need to reverse then the entity + this.endPoint = start; + reverse(e); + this.elements.add(e); + + return true; + } + + return false; + } + + /** + * Gets the start point. + * + * @return the start point + */ + public Point getStartPoint() { return this.startPoint; } + + /** + * Gets the end point. + * + * @return the end point + */ + public Point getEndPoint() { return this.endPoint; } + + /** + * Gets the element iterator. + * + * @return the element iterator + */ + public Iterator getElementIterator() { return this.elements.iterator(); } + + /** + * Connect. + * + * @param queue + * the queue + * @return true, if successful + */ + public boolean connect(final PolylineQueue queue) { + if (DXFUtils.equals(queue.getStartPoint(), this.endPoint, radius)) { + // add to the end + add(queue); + + return true; + } + if (DXFUtils.equals(queue.getEndPoint(), this.startPoint, radius)) { + // insert before + insertBefore(queue); + + return true; + } + if (DXFUtils.equals(queue.getStartPoint(), this.startPoint, radius)) { + queue.reverse(); + insertBefore(queue); + + return true; + } else if (DXFUtils.equals(queue.getEndPoint(), this.endPoint, radius)) { + queue.reverse(); + add(queue); + + return true; + } + + return false; + } + + /** + * Creates the DXF polyline. + * + * @param layer + * the layer + */ + public void createDXFPolyline(final DXFLayer layer) { + // create the polyline and remove the entity + DXFPolyline pline = new DXFPolyline(); + DXFVertex first = new DXFVertex(this.startPoint); + pline.addVertex(first); + + Iterator i = this.elements.iterator(); + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + + if (DXFConstants.ENTITY_TYPE_LINE.equals(e.getType())) { + DXFLine line = (DXFLine) e; + first = new DXFVertex(line.getEndPoint()); + pline.addVertex(first); + } else if (DXFConstants.ENTITY_TYPE_POLYLINE.equals(e.getType()) + || DXFConstants.ENTITY_TYPE_LWPOLYLINE.equals(e.getType())) { + DXFPolyline pl = (DXFPolyline) e; + double bulge = pl.getVertex(0).getBulge(); + + if (bulge != 0.0) { first.setBulge(bulge); } + + for (int x = 1; x < pl.getVertexCount(); x++) { + first = pl.getVertex(x); + pline.addVertex(first); + } + } else if (DXFConstants.ENTITY_TYPE_ARC.equals(e.getType())) { + DXFArc arc = (DXFArc) e; + + if (arc.getTotalAngle() > 0.0) { + double h = arc.getRadius() * (1 - Math.cos(Math.toRadians(arc.getTotalAngle() / 2))); + double chordLength = arc.getChordLength(); + + if (DXFUtils.equals(arc.getStartPoint(), first.getPoint(), radius)) { + // the last point is our start point, + // which is always set + // we have to calculate the bulge + first.setBulge(2 * h / chordLength); + first = new DXFVertex(arc.getEndPoint()); + } else { + // reverse the arc, we change the start/end points + // and set the bulge to >0 + first.setBulge(-1.0 * (2 * h / chordLength)); + + first = new DXFVertex(arc.getStartPoint()); + } + pline.addVertex(first); + } + } + + // remove from layer + layer.removeDXFEntity(e); + } + + // add the new polyline to the layer + pline.setLayerName(layer.getName()); + layer.addDXFEntity(pline); + } + + /** + * Reverse. + * + * @param entity + * the entity + */ + protected void reverse(final DXFEntity entity) { + if (DXFConstants.ENTITY_TYPE_LINE.equals(entity.getType())) { + DXFUtils.reverseDXFLine((DXFLine) entity); + } else if (DXFConstants.ENTITY_TYPE_POLYLINE.equals(entity.getType()) + || DXFConstants.ENTITY_TYPE_LWPOLYLINE.equals(entity.getType())) { + DXFUtils.reverseDXFPolyline((DXFPolyline) entity); + } else if (DXFConstants.ENTITY_TYPE_ARC.equals(entity.getType())) { + // we cannot reverse a DXF ARC + } + } + + /** + * Reverse. + */ + protected void reverse() { + Point p = this.endPoint; + this.endPoint = this.startPoint; + this.startPoint = p; + + // reverse the list and all entities + int last = this.elements.size() - 1; + + for (int i = 0; i < last + 1; i++) { + DXFEntity first = this.elements.get(i); + this.reverse(first); + + if (i < last) { + DXFEntity e = this.elements.set(last, first); + this.reverse(e); + this.elements.set(i, e); + last--; + } + } + } + + /** + * Insert the PolylineQueue before the first element. + * + * @param queue + */ + public void insertBefore(final PolylineQueue queue) { + this.startPoint = queue.getStartPoint(); + + Iterator i = queue.getElementIterator(); + int x = 0; + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + this.elements.add(x, e); + x++; + } + } + + /** + * Adds the queue to the end. + * + * @param queue + */ + public void add(final PolylineQueue queue) { + this.endPoint = queue.getEndPoint(); + + Iterator i = queue.getElementIterator(); + + while (i.hasNext()) { + DXFEntity e = (DXFEntity) i.next(); + this.elements.add(e); + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/CodePageParser.java b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/CodePageParser.java index bf2c3e2a6e..6dcf39e025 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/CodePageParser.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/CodePageParser.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * CodePageParser.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.tools; import java.io.BufferedReader; @@ -20,69 +15,79 @@ import msi.gama.ext.kabeja.dxf.DXFConstants; - /** * @author Simon Mieth * */ public class CodePageParser { - public static final String CODEPAGE_CODE = "$DWGCODEPAGE"; - public static final String GROUPCODE = "3"; - private static final String[] prefix = { "ansi_", "dos" }; - private static final String javaPrefix = "Cp"; - - public String parseEncoding(BufferedReader reader) { - String encoding = ""; - - try { - String line = null; - String code; - String value; - boolean next = true; - boolean codepage = false; - boolean key = true; - String currentKey = null; - - while (((line = reader.readLine()) != null) && next) { - line = line.trim(); - - if (key) { - currentKey = line; - key = false; - } else { - key = true; - - // we read the first section - if (DXFConstants.SECTION_END.equals(line)) { - return encoding; - } else if (CODEPAGE_CODE.equals(line)) { - codepage = true; - } else if (codepage && currentKey.equals("3")) { - // the encoding - return translateCodePage(line); - } else if (DXFConstants.SECTION_CLASSES.equals(line) || - DXFConstants.SECTION_BLOCKS.equals(line) || - DXFConstants.SECTION_ENTITIES.equals(line)) { - return encoding; - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } - - return encoding; - } - - public String translateCodePage(String cp) { - String c = cp.toLowerCase(); - - for (int i = 0; i < prefix.length; i++) { - if (c.startsWith(prefix[i])) { - return javaPrefix + cp.substring(prefix[i].length()); - } - } - - return cp; - } + + /** The Constant CODEPAGE_CODE. */ + public static final String CODEPAGE_CODE = "$DWGCODEPAGE"; + + /** The Constant GROUPCODE. */ + public static final String GROUPCODE = "3"; + + /** The Constant prefix. */ + private static final String[] prefix = { "ansi_", "dos" }; + + /** The Constant javaPrefix. */ + private static final String javaPrefix = "Cp"; + + /** + * Parses the encoding. + * + * @param reader the reader + * @return the string + */ + public String parseEncoding(final BufferedReader reader) { + String encoding = ""; + + try { + String line = null; + boolean next = true; + boolean codepage = false; + boolean key = true; + String currentKey = null; + + while ((line = reader.readLine()) != null && next) { + line = line.trim(); + + if (key) { + currentKey = line; + key = false; + } else { + key = true; + + // we read the first section + if (DXFConstants.SECTION_END.equals(line)) return encoding; + if (CODEPAGE_CODE.equals(line)) { + codepage = true; + } else if (codepage && "3".equals(currentKey)) + // the encoding + return translateCodePage(line); + else if (DXFConstants.SECTION_CLASSES.equals(line) || DXFConstants.SECTION_BLOCKS.equals(line) + || DXFConstants.SECTION_ENTITIES.equals(line)) + return encoding; + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return encoding; + } + + /** + * Translate code page. + * + * @param cp the cp + * @return the string + */ + public String translateCodePage(final String cp) { + String c = cp.toLowerCase(); + + for (String element : prefix) { if (c.startsWith(element)) return javaPrefix + cp.substring(element.length()); } + + return cp; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/ConfigHelper.java b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/ConfigHelper.java index d185c8a83e..f39c4eaf2c 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/ConfigHelper.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/ConfigHelper.java @@ -1,60 +1,58 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * ConfigHelper.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.tools; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; -import org.xml.sax.helpers.XMLReaderFactory; - /** * @author Simon Mieth * */ public class ConfigHelper { - public static final String JAVA_14_SAX_DRIVER = "org.apache.crimson.parser.XMLReaderImpl"; - public static final String JAVA_15_SAX_DRIVER = "com.sun.org.apache.xerces.internal.parsers.SAXParser"; - - public static String getSAXSDDriver() { - // check for version 1.4 and above - String ver = System.getProperty("java.version"); - String parser = null; - - try { - parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader() - .getClass().getName(); - - XMLReader r = XMLReaderFactory.createXMLReader(parser); - } catch (SAXException e) { - e.printStackTrace(); - } catch (ParserConfigurationException e) { - e.printStackTrace(); - } - - // if (ver.startsWith("1.2") || ver.startsWith("1.3")) { - // parser = System.getProperty("org.xml.sax.driver"); - // } else if (ver.startsWith("1.4")) { - // // jdk 1.4 uses crimson - // parser = JAVA_14_SAX_DRIVER; - // } else if (ver.startsWith("1.5")) { - // parser = JAVA_15_SAX_DRIVER; - // } - return parser; - } + + /** The Constant JAVA_14_SAX_DRIVER. */ + public static final String JAVA_14_SAX_DRIVER = "org.apache.crimson.parser.XMLReaderImpl"; + + /** The Constant JAVA_15_SAX_DRIVER. */ + public static final String JAVA_15_SAX_DRIVER = "com.sun.org.apache.xerces.internal.parsers.SAXParser"; + + /** + * Gets the SAXSD driver. + * + * @return the SAXSD driver + */ + public static String getSAXSDDriver() { + // check for version 1.4 and above + // String ver = System.getProperty("java.version"); + String parser = null; + + try { + parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader().getClass().getName(); + + // XMLReader r = XMLReaderFactory.createXMLReader(parser); + } catch (SAXException | ParserConfigurationException e) { + e.printStackTrace(); + } + + // if (ver.startsWith("1.2") || ver.startsWith("1.3")) { + // parser = System.getProperty("org.xml.sax.driver"); + // } else if (ver.startsWith("1.4")) { + // // jdk 1.4 uses crimson + // parser = JAVA_14_SAX_DRIVER; + // } else if (ver.startsWith("1.5")) { + // parser = JAVA_15_SAX_DRIVER; + // } + return parser; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/FontManager.java b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/FontManager.java index 8b03e9e0ca..4883741f1c 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/FontManager.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/FontManager.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * FontManager.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.tools; import java.io.BufferedReader; @@ -22,94 +17,117 @@ import java.io.InputStreamReader; import java.util.Hashtable; - /** * @author Simon Mieth * */ public class FontManager { - private static FontManager instance = new FontManager(); - private String fontDescription = "conf/font.properties"; - private Hashtable fontProperties = new Hashtable(); - - private FontManager() { - loadFontDescription(); - } - - public void setFontDescription(String file) { - this.fontDescription = file; - loadFontDescription(); - } - - private void loadFontDescription() { - fontProperties.clear(); - - try { - InputStream stream = this.getClass() - .getResourceAsStream(this.fontDescription); - - if (stream == null) { - try { - stream = new FileInputStream(this.fontDescription); - } catch (FileNotFoundException e1) { - } - } - - if (stream != null) { - BufferedReader in = new BufferedReader(new InputStreamReader( - stream)); - String line = null; - - while ((line = in.readLine()) != null) { - int index = line.indexOf("="); - - if (index >= 0) { - String font = line.substring(0, index).trim() - .toLowerCase(); - String svgFont = line.substring(index + 1).trim(); - fontProperties.put(font, svgFont); - } - } - } else { - // System.out.println("no font.properties"); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static FontManager getInstance() { - return instance; - } - - /** - * Query if a SVG font description exists for the given shx font. - * - * @param font - * The font.shx or font - * @return - */ - public boolean hasFontDescription(String font) { - font = getFontKey(font); - - if (fontProperties.containsKey(font)) { - return true; - } - - return false; - } - - public String getFontDescription(String font) { - return (String) fontProperties.get(getFontKey(font)); - } - - private String getFontKey(String font) { - font = font.toLowerCase(); - - if (font.endsWith(".shx")) { - font = font.substring(0, font.indexOf(".shx")); - } - - return font; - } + + /** The instance. */ + private static FontManager instance = new FontManager(); + + /** The font description. */ + private String fontDescription = "conf/font.properties"; + + /** The font properties. */ + private final Hashtable fontProperties = new Hashtable<>(); + + /** + * Instantiates a new font manager. + */ + private FontManager() { + loadFontDescription(); + } + + /** + * Sets the font description. + * + * @param file the new font description + */ + public void setFontDescription(final String file) { + this.fontDescription = file; + loadFontDescription(); + } + + /** + * Load font description. + */ + private void loadFontDescription() { + fontProperties.clear(); + + try { + InputStream stream = this.getClass().getResourceAsStream(this.fontDescription); + + if (stream == null) { + try { + stream = new FileInputStream(this.fontDescription); + } catch (FileNotFoundException e1) {} + } + + if (stream != null) { + BufferedReader in = new BufferedReader(new InputStreamReader(stream)); + String line = null; + + while ((line = in.readLine()) != null) { + int index = line.indexOf("="); + + if (index >= 0) { + String font = line.substring(0, index).trim().toLowerCase(); + String svgFont = line.substring(index + 1).trim(); + fontProperties.put(font, svgFont); + } + } + } else { + // System.out.println("no font.properties"); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * Gets the single instance of FontManager. + * + * @return single instance of FontManager + */ + public static FontManager getInstance() { return instance; } + + /** + * Query if a SVG font description exists for the given shx font. + * + * @param font + * The font.shx or font + * @return + */ + public boolean hasFontDescription(String font) { + font = getFontKey(font); + + if (fontProperties.containsKey(font)) return true; + + return false; + } + + /** + * Gets the font description. + * + * @param font the font + * @return the font description + */ + public String getFontDescription(final String font) { + return fontProperties.get(getFontKey(font)); + } + + /** + * Gets the font key. + * + * @param font the font + * @return the font key + */ + private String getFontKey(String font) { + font = font.toLowerCase(); + + if (font.endsWith(".shx")) { font = font.substring(0, font.indexOf(".shx")); } + + return font; + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXFilterConfig.java b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXFilterConfig.java index d909d0bb39..f5d9aab99d 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXFilterConfig.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXFilterConfig.java @@ -1,59 +1,74 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * SAXFilterConfig.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.tools; import java.util.HashMap; import java.util.Map; - /** * @author Simon Mieth * */ public class SAXFilterConfig { - private Map properties; - private String filterName; - - public SAXFilterConfig(Map properties) { - this.properties = properties; - } - - public SAXFilterConfig() { - this(new HashMap()); - } - - public Map getProperties() { - return this.properties; - } - - public void addProperty(String name, String value) { - this.properties.put(name, value); - } - - /** - * @return Returns the filterName. - */ - public String getFilterName() { - return filterName; - } - - /** - * @param filterName The filterName to set. - */ - public void setFilterName(String filterName) { - this.filterName = filterName; - } + + /** The properties. */ + private final Map properties; + + /** The filter name. */ + private String filterName; + + /** + * Instantiates a new SAX filter config. + * + * @param properties + * the properties + */ + public SAXFilterConfig(final Map properties) { + this.properties = properties; + } + + /** + * Instantiates a new SAX filter config. + */ + public SAXFilterConfig() { + this(new HashMap<>()); + } + + /** + * Gets the properties. + * + * @return the properties + */ + public Map getProperties() { return this.properties; } + + /** + * Adds the property. + * + * @param name + * the name + * @param value + * the value + */ + public void addProperty(final String name, final String value) { + this.properties.put(name, value); + } + + /** + * @return Returns the filterName. + */ + public String getFilterName() { return filterName; } + + /** + * @param filterName + * The filterName to set. + */ + public void setFilterName(final String filterName) { this.filterName = filterName; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXProcessingManagerBuilder.java b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXProcessingManagerBuilder.java index 55c64ccda6..545c74f2ed 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXProcessingManagerBuilder.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXProcessingManagerBuilder.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ +/******************************************************************************************************* + * + * SAXProcessingManagerBuilder.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation + * platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.tools; import java.io.IOException; @@ -23,6 +18,13 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParserFactory; +import org.xml.sax.Attributes; +import org.xml.sax.ContentHandler; +import org.xml.sax.InputSource; +import org.xml.sax.Locator; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + import msi.gama.ext.kabeja.parser.Parser; import msi.gama.ext.kabeja.parser.SAXParserBuilder; import msi.gama.ext.kabeja.processing.PostProcessor; @@ -33,79 +35,139 @@ import msi.gama.ext.kabeja.xml.SAXFilter; import msi.gama.ext.kabeja.xml.SAXGenerator; import msi.gama.ext.kabeja.xml.SAXSerializer; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.InputSource; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; /** * @author Simon Mieth - * + * */ public class SAXProcessingManagerBuilder implements ContentHandler { + + /** The xmlns kabeja processing. */ public static String XMLNS_KABEJA_PROCESSING = "http://kabeja.org/processing/1.0"; + + /** The Constant ELEMENT_CONFIGURATION. */ public static final String ELEMENT_CONFIGURATION = "configuration"; + + /** The Constant ELEMENT_PARSER. */ public static final String ELEMENT_PARSER = "parser"; + + /** The Constant ELEMENT_PARSERS. */ public static final String ELEMENT_PARSERS = "parsers"; + + /** The Constant ELEMENT_SAXSERIALIZER. */ public static final String ELEMENT_SAXSERIALIZER = "serializer"; + + /** The Constant ELEMENT_SAXSERIALIZERS. */ public static final String ELEMENT_SAXSERIALIZERS = "serializers"; + + /** The Constant ELEMENT_SAXFILTER. */ public static final String ELEMENT_SAXFILTER = "filter"; + + /** The Constant ELEMENT_FILTER. */ public static final String ELEMENT_FILTER = "filter"; + + /** The Constant ELEMENT_SAXFILTERS. */ public static final String ELEMENT_SAXFILTERS = "filters"; + + /** The Constant ELEMENT_PIPELINE. */ public static final String ELEMENT_PIPELINE = "pipeline"; + + /** The Constant ELEMENT_PIPELINES. */ public static final String ELEMENT_PIPELINES = "pipelines"; + + /** The Constant ELEMENT_SERIALIZE. */ public static final String ELEMENT_SERIALIZE = "serialize"; + + /** The Constant ELEMENT_PROPERTY. */ public static final String ELEMENT_PROPERTY = "property"; + + /** The Constant ELEMENT_POSTPROCESSOR. */ public static final String ELEMENT_POSTPROCESSOR = "postprocessor"; + + /** The Constant ELEMENT_POSTPROCESS. */ public static final String ELEMENT_POSTPROCESS = "postprocess"; + + /** The Constant ELEMENT_AGGREGATE. */ public static final String ELEMENT_AGGREGATE = "aggregate"; + + /** The Constant ELEMENT_SAXGENERATOR. */ public static final String ELEMENT_SAXGENERATOR = "generator"; + + /** The Constant ELEMENT_GENERATE. */ public static final String ELEMENT_GENERATE = "generate"; + + /** The Constant ATTRIBUTE_NAME. */ public static final String ATTRIBUTE_NAME = "name"; + + /** The Constant ATTRIBUTE_CLASS. */ public static final String ATTRIBUTE_CLASS = "class"; + + /** The Constant ATTRIBUTE_VALUE. */ public static final String ATTRIBUTE_VALUE = "value"; + + /** The Constant ATTRIBUTE_DESCRIPTION. */ public static final String ATTRIBUTE_DESCRIPTION = "description"; + + /** The manager. */ private ProcessingManager manager; + + /** The saxfilter. */ private SAXFilter saxfilter; + + /** The saxserializer. */ private SAXSerializer saxserializer; + + /** The postprocessor. */ private PostProcessor postprocessor; + + /** The saxgenerator. */ private SAXGenerator saxgenerator; + + /** The aggregator. */ private AggregatorGenerator aggregator; - private Map properties; - private StringBuffer buf = new StringBuffer(); + + /** The properties. */ + private Map properties; + + /** The name. */ + // private StringBuffer buf = new StringBuffer(); private String name; + + /** The pipeline. */ private ProcessPipeline pipeline; + + /** The config. */ private boolean config = false; + + /** The aggregate. */ private boolean aggregate = false; + + /** The parser builder. */ protected SAXParserBuilder parserBuilder; /* * (non-Javadoc) - * + * * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ - public void characters(char[] ch, int start, int length) - throws SAXException { - } + @Override + public void characters(final char[] ch, final int start, final int length) throws SAXException {} /* * (non-Javadoc) - * + * * @see org.xml.sax.ContentHandler#endDocument() */ - public void endDocument() throws SAXException { - } + @Override + public void endDocument() throws SAXException {} /* * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#endElement(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ - public void endElement(String namespaceURI, String localName, String qName) - throws SAXException { + @Override + public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException { if (namespaceURI.equals(XMLNS_KABEJA_PROCESSING)) { if (ELEMENT_SAXFILTER.equals(localName) && this.config) { this.saxfilter.setProperties(properties); @@ -116,8 +178,7 @@ public void endElement(String namespaceURI, String localName, String qName) } else if (ELEMENT_PIPELINE.equals(localName)) { this.manager.addProcessPipeline(this.pipeline); } else if (ELEMENT_SERIALIZE.equals(localName)) { - this.pipeline.setSAXSerializer(this.manager - .getSAXSerializer(this.name)); + this.pipeline.setSAXSerializer(this.manager.getSAXSerializer(this.name)); this.pipeline.setSAXSerializerProperties(this.properties); } else if (ELEMENT_FILTER.equals(localName)) { @@ -125,8 +186,7 @@ public void endElement(String namespaceURI, String localName, String qName) config.setFilterName(this.name); this.pipeline.addSAXFilterConfig(config); } else if (ELEMENT_POSTPROCESS.equals(localName)) { - PostProcessorConfig config = new PostProcessorConfig( - this.properties); + PostProcessorConfig config = new PostProcessorConfig(this.properties); config.setPostProcessorName(this.name); this.pipeline.addPostProcessorConfig(config); } else if (ELEMENT_POSTPROCESSOR.equals(localName)) { @@ -136,12 +196,10 @@ public void endElement(String namespaceURI, String localName, String qName) this.config = false; } else if (ELEMENT_GENERATE.equals(localName)) { if (this.aggregate) { - this.aggregator.addSAXGenerator(this.manager - .getSAXGenerator(this.name)); + this.aggregator.addSAXGenerator(this.manager.getSAXGenerator(this.name)); } else { this.pipeline.setSAXGeneratorProperties(this.properties); - this.pipeline.setSAXGenerator(this.manager - .getSAXGenerator(this.name)); + this.pipeline.setSAXGenerator(this.manager.getSAXGenerator(this.name)); } } else if (ELEMENT_SAXGENERATOR.equals(localName)) { this.saxgenerator.setProperties(this.properties); @@ -150,7 +208,7 @@ public void endElement(String namespaceURI, String localName, String qName) } else if (namespaceURI.equals(SAXParserBuilder.XMLNS_KABEJA_PARSER)) { this.parserBuilder.endElement(namespaceURI, localName, qName); - if (localName.equals(ELEMENT_PARSER)) { + if (ELEMENT_PARSER.equals(localName)) { // finish up the ParserBuilder and // add the parse to ProcessManager this.parserBuilder.endDocument(); @@ -163,111 +221,105 @@ public void endElement(String namespaceURI, String localName, String qName) /* * (non-Javadoc) - * + * * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ - public void endPrefixMapping(String prefix) throws SAXException { - } + @Override + public void endPrefixMapping(final String prefix) throws SAXException {} /* * (non-Javadoc) - * + * * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ - public void ignorableWhitespace(char[] ch, int start, int length) - throws SAXException { - } + @Override + public void ignorableWhitespace(final char[] ch, final int start, final int length) throws SAXException {} /* * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, - * java.lang.String) + * + * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */ - public void processingInstruction(String target, String data) - throws SAXException { - } + @Override + public void processingInstruction(final String target, final String data) throws SAXException {} /* * (non-Javadoc) - * + * * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) */ - public void setDocumentLocator(Locator locator) { - } + @Override + public void setDocumentLocator(final Locator locator) {} /* * (non-Javadoc) - * + * * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ - public void skippedEntity(String name) throws SAXException { - } + @Override + public void skippedEntity(final String name) throws SAXException {} /* * (non-Javadoc) - * + * * @see org.xml.sax.ContentHandler#startDocument() */ + @Override public void startDocument() throws SAXException { manager = new ProcessingManager(); } /* * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#startElement(java.lang.String, - * java.lang.String, java.lang.String, org.xml.sax.Attributes) + * + * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, + * org.xml.sax.Attributes) */ - public void startElement(String namespaceURI, String localName, - String qName, Attributes atts) throws SAXException { + @Override + public void startElement(final String namespaceURI, final String localName, final String qName, + final Attributes atts) throws SAXException { if (namespaceURI.equals(XMLNS_KABEJA_PROCESSING)) { if (ELEMENT_SAXFILTER.equals(localName) && this.config) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); name = atts.getValue(ATTRIBUTE_NAME); - saxfilter = (SAXFilter) createInstance(atts - .getValue(ATTRIBUTE_CLASS)); + saxfilter = (SAXFilter) createInstance(atts.getValue(ATTRIBUTE_CLASS)); } else if (ELEMENT_SAXSERIALIZER.equals(localName)) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); name = atts.getValue(ATTRIBUTE_NAME); - saxserializer = (SAXSerializer) createInstance(atts - .getValue(ATTRIBUTE_CLASS)); + saxserializer = (SAXSerializer) createInstance(atts.getValue(ATTRIBUTE_CLASS)); } else if (ELEMENT_POSTPROCESSOR.equals(localName)) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); this.name = atts.getValue(ATTRIBUTE_NAME); - String clazz = (atts.getValue(ATTRIBUTE_CLASS)); + String clazz = atts.getValue(ATTRIBUTE_CLASS); postprocessor = (PostProcessor) createInstance(clazz); } else if (ELEMENT_PIPELINE.equals(localName)) { this.aggregate = false; this.pipeline = new ProcessPipeline(); this.pipeline.setName(atts.getValue(ATTRIBUTE_NAME)); String des = atts.getValue(ATTRIBUTE_DESCRIPTION); - if (des != null) { - this.pipeline.setDescription(des); - } + if (des != null) { this.pipeline.setDescription(des); } } else if (ELEMENT_SERIALIZE.equals(localName)) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); this.name = atts.getValue(ATTRIBUTE_NAME); } else if (ELEMENT_FILTER.equals(localName)) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); name = atts.getValue(ATTRIBUTE_NAME); } else if (ELEMENT_PROPERTY.equals(localName)) { - this.properties.put(atts.getValue(ATTRIBUTE_NAME), atts - .getValue(ATTRIBUTE_VALUE)); + this.properties.put(atts.getValue(ATTRIBUTE_NAME), atts.getValue(ATTRIBUTE_VALUE)); } else if (ELEMENT_POSTPROCESS.equals(localName)) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); name = atts.getValue(ATTRIBUTE_NAME); } else if (ELEMENT_CONFIGURATION.equals(localName)) { this.config = true; } else if (ELEMENT_SAXGENERATOR.equals(localName)) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); this.name = atts.getValue(ATTRIBUTE_NAME); - String clazz = (atts.getValue(ATTRIBUTE_CLASS)); + String clazz = atts.getValue(ATTRIBUTE_CLASS); this.saxgenerator = (SAXGenerator) createInstance(clazz); } else if (ELEMENT_GENERATE.equals(localName)) { - this.properties = new HashMap(); + this.properties = new HashMap<>(); this.name = atts.getValue(ATTRIBUTE_NAME); } else if (ELEMENT_AGGREGATE.equals(localName)) { this.aggregate = true; @@ -275,41 +327,42 @@ public void startElement(String namespaceURI, String localName, this.pipeline.setSAXGenerator(this.aggregator); } } else if (namespaceURI.equals(SAXParserBuilder.XMLNS_KABEJA_PARSER)) { - if (localName.equals(ELEMENT_PARSER)) { + if (ELEMENT_PARSER.equals(localName)) { this.parserBuilder = new SAXParserBuilder(); this.parserBuilder.startDocument(); } - this.parserBuilder.startElement(namespaceURI, localName, qName, - atts); + this.parserBuilder.startElement(namespaceURI, localName, qName, atts); } } /* * (non-Javadoc) - * - * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, - * java.lang.String) + * + * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ - public void startPrefixMapping(String prefix, String uri) - throws SAXException { - } + @Override + public void startPrefixMapping(final String prefix, final String uri) throws SAXException {} - public ProcessingManager getManager() { - return this.manager; - } + /** + * Gets the manager. + * + * @return the manager + */ + public ProcessingManager getManager() { return this.manager; } - protected Object createInstance(String clazz) { + /** + * Creates the instance. + * + * @param clazz + * the clazz + * @return the object + */ + protected Object createInstance(final String clazz) { try { Class cl = this.getClass().getClassLoader().loadClass(clazz); - Object obj = cl.newInstance(); - - return obj; - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } catch (InstantiationException e) { - e.printStackTrace(); - } catch (IllegalAccessException e) { + return cl.newInstance(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { e.printStackTrace(); } @@ -317,12 +370,12 @@ protected Object createInstance(String clazz) { } /** - * + * * @param in * the InputStream * @return The ProcessingManager build from the XML description */ - public static ProcessingManager buildFromStream(InputStream in) { + public static ProcessingManager buildFromStream(final InputStream in) { SAXProcessingManagerBuilder builder = new SAXProcessingManagerBuilder(); try { @@ -331,12 +384,10 @@ public static ProcessingManager buildFromStream(InputStream in) { // factory.setXIncludeAware(true); try { - factory.setFeature("http://apache.org/xml/features/xinclude", - true); + factory.setFeature("http://apache.org/xml/features/xinclude", true); } catch (Exception e) { // OK older jaxp - System.out - .println("No XInclude support (use JAXP 1.4 or later for XInclude)"); + System.out.println("No XInclude support (use JAXP 1.4 or later for XInclude)"); } try { @@ -347,9 +398,7 @@ public static ProcessingManager buildFromStream(InputStream in) { } catch (ParserConfigurationException e) { e.printStackTrace(); } - } catch (SAXException e) { - e.printStackTrace(); - } catch (IOException ioe) { + } catch (SAXException | IOException ioe) { ioe.printStackTrace(); } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXSerializerConfig.java b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXSerializerConfig.java index 4517968dc4..3e6a7a7162 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXSerializerConfig.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/tools/SAXSerializerConfig.java @@ -1,51 +1,55 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * SAXSerializerConfig.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.tools; import java.util.HashMap; import java.util.Map; - /** * @author Simon Mieth * */ public class SAXSerializerConfig { - private Map properties = new HashMap(); - private String saxSerializerName; - - public Map getProperties() { - return this.properties; - } - - public void addProperty(String name, String value) { - this.properties.put(name, value); - } - - /** - * @return Returns the filterName. - */ - public String getSAXSerializerName() { - return saxSerializerName; - } - - /** - * @param filterName The filterName to set. - */ - public void setSAXSerializerName(String filterName) { - this.saxSerializerName = filterName; - } + + /** The properties. */ + private final Map properties = new HashMap<>(); + + /** The sax serializer name. */ + private String saxSerializerName; + + /** + * Gets the properties. + * + * @return the properties + */ + public Map getProperties() { return this.properties; } + + /** + * Adds the property. + * + * @param name the name + * @param value the value + */ + public void addProperty(final String name, final String value) { + this.properties.put(name, value); + } + + /** + * @return Returns the filterName. + */ + public String getSAXSerializerName() { return saxSerializerName; } + + /** + * @param filterName + * The filterName to set. + */ + public void setSAXSerializerName(final String filterName) { this.saxSerializerName = filterName; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/xml/AggregatorGenerator.java b/msi.gama.ext/src/msi/gama/ext/kabeja/xml/AggregatorGenerator.java index 924fc43d36..771800900b 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/xml/AggregatorGenerator.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/xml/AggregatorGenerator.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * AggregatorGenerator.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.xml; import java.util.ArrayList; @@ -20,60 +15,82 @@ import java.util.List; import java.util.Map; -import msi.gama.ext.kabeja.dxf.DXFDocument; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; +import msi.gama.ext.kabeja.dxf.DXFDocument; -public class AggregatorGenerator extends AbstractSAXFilter - implements SAXGenerator { - public final static String ROOT_ELEMENT = "aggregate"; - public final static String NAMESPACE = "http://kabeja.org/aggregate"; - protected List generators = new ArrayList(); - protected DXFDocument doc; - - public void generate(DXFDocument doc, ContentHandler handler, Map context) - throws SAXException { - this.setContentHandler(handler); - this.doc = doc; - - try { - handler.startDocument(); - - String raw = NAMESPACE + ":" + ROOT_ELEMENT; - handler.startElement(NAMESPACE, raw, ROOT_ELEMENT, - new AttributesImpl()); - doGenerate(); - handler.endElement(NAMESPACE, raw, ROOT_ELEMENT); - handler.endDocument(); - } catch (SAXException e) { - e.printStackTrace(); - } - } - - protected void doGenerate() throws SAXException { - Iterator i = this.generators.iterator(); - - while (i.hasNext()) { - SAXGenerator generator = (SAXGenerator) i.next(); - generator.generate(this.doc, this, null); - } - } - - public void endDocument() throws SAXException { - // ignore - } - - public void startDocument() throws SAXException { - // ignore - } - - public void addSAXGenerator(SAXGenerator generator) { - this.generators.add(generator); - } - - public Map getProperties() { - return this.properties; - } +/** + * The Class AggregatorGenerator. + */ +public class AggregatorGenerator extends AbstractSAXFilter implements SAXGenerator { + + /** The Constant ROOT_ELEMENT. */ + public final static String ROOT_ELEMENT = "aggregate"; + + /** The Constant NAMESPACE. */ + public final static String NAMESPACE = "http://kabeja.org/aggregate"; + + /** The generators. */ + protected List generators = new ArrayList<>(); + + /** The doc. */ + protected DXFDocument doc; + + @Override + public void generate(final DXFDocument doc, final ContentHandler handler, final Map context) throws SAXException { + this.setContentHandler(handler); + this.doc = doc; + + try { + handler.startDocument(); + + String raw = NAMESPACE + ":" + ROOT_ELEMENT; + handler.startElement(NAMESPACE, raw, ROOT_ELEMENT, new AttributesImpl()); + doGenerate(); + handler.endElement(NAMESPACE, raw, ROOT_ELEMENT); + handler.endDocument(); + } catch (SAXException e) { + e.printStackTrace(); + } + } + + /** + * Do generate. + * + * @throws SAXException + * the SAX exception + */ + protected void doGenerate() throws SAXException { + Iterator i = this.generators.iterator(); + + while (i.hasNext()) { + SAXGenerator generator = (SAXGenerator) i.next(); + generator.generate(this.doc, this, null); + } + } + + @Override + public void endDocument() throws SAXException { + // ignore + } + + @Override + public void startDocument() throws SAXException { + // ignore + } + + /** + * Adds the SAX generator. + * + * @param generator + * the generator + */ + public void addSAXGenerator(final SAXGenerator generator) { + this.generators.add(generator); + } + + @Override + public Map getProperties() { return this.properties; } } diff --git a/msi.gama.ext/src/msi/gama/ext/kabeja/xml/SAXPrettyOutputter.java b/msi.gama.ext/src/msi/gama/ext/kabeja/xml/SAXPrettyOutputter.java index bc7fec6684..9e73754674 100644 --- a/msi.gama.ext/src/msi/gama/ext/kabeja/xml/SAXPrettyOutputter.java +++ b/msi.gama.ext/src/msi/gama/ext/kabeja/xml/SAXPrettyOutputter.java @@ -1,18 +1,13 @@ -/* - Copyright 2005 Simon Mieth - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -*/ +/******************************************************************************************************* + * + * SAXPrettyOutputter.java, in msi.gama.ext, is part of the source code of the GAMA modeling and simulation platform + * (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kabeja.xml; import java.io.BufferedOutputStream; @@ -28,313 +23,354 @@ import org.xml.sax.Locator; import org.xml.sax.SAXException; - /** *

- * This outputs a SAXStream to an OutputStream with the given encoding or - * otherwise with the default encoding (utf-8). + * This outputs a SAXStream to an OutputStream with the given encoding or otherwise with the default encoding (utf-8). *

*

- * Note: Not all features are implemented, so if you use this with other - * SAXStreams others then the Kabeja-SAXStream you will get broken - * XML-Documents. + * Note: Not all features are implemented, so if you use this with other SAXStreams others then the + * Kabeja-SAXStream you will get broken XML-Documents. *

* * @author Simon Mieth * */ -public class SAXPrettyOutputter extends AbstractSAXSerializer - implements SAXSerializer { - public static final String DEFAULT_ENCODING = "UTF-8"; - public static final String SUFFIX = "svg"; - public static final String SUFFIX_GZIP = "svgz"; - public static final String MIMETYPE = "text/svg"; - public static final String PROPERTY_ENCODING = "encoding"; - public static final String PROPERTY_GZIP = "gzip"; - private OutputStreamWriter out; - private String encoding; - private String dtd; - private int indent = 0; - private boolean parent = false; - private ArrayList textContentList = new ArrayList(); - protected HashMap rootxmlns = new HashMap(); - protected boolean gzip = false; - - public SAXPrettyOutputter(OutputStream output, String encoding) { - this.encoding = encoding; - this.setOutput(output); - } - - /** - * - */ - public SAXPrettyOutputter(OutputStream out) { - this(out, DEFAULT_ENCODING); - } - - public SAXPrettyOutputter() { - this.encoding = DEFAULT_ENCODING; - } - - public void characters(char[] ch, int start, int length) - throws SAXException { - try { - if (length > 0) { - if (parent) { - this.out.write(">"); - parent = false; - } - - char[] enc = encodeXML(new String(ch, 0, length)).toCharArray(); - this.out.write(enc, start, enc.length); - - // textNode in this context - textContentList.set(textContentList.size() - 1, - new Boolean(true)); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void endDocument() throws SAXException { - try { - this.out.flush(); - this.out.close(); - - textContentList.clear(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void endElement(String namespaceURI, String localName, String qName) - throws SAXException { - try { - if (parent) { - this.out.write("/>"); - } else { - // check for textNodes in this context - Boolean b = (Boolean) textContentList.remove(textContentList.size() - - 1); - - if (b.booleanValue()) { - this.out.write(""); - } else { - // there was no textNode we can create a new line - this.out.write('\n'); - indentOutput(indent); - this.out.write(""); - } - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - indent--; - parent = false; - } - - public void endPrefixMapping(String prefix) throws SAXException { - } - - public void ignorableWhitespace(char[] ch, int start, int length) - throws SAXException { - } - - public void processingInstruction(String target, String data) - throws SAXException { - } - - public void setDocumentLocator(Locator locator) { - } - - public void skippedEntity(String name) throws SAXException { - } - - public void startDocument() throws SAXException { - indent = 0; - - try { - this.out.write(""); - - if (this.dtd != null) { - this.out.write("\n"); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void startElement(String namespaceURI, String localName, - String qName, Attributes atts) throws SAXException { - this.indent++; - - try { - if (this.parent) { - // we are nested - this.out.write(">"); - } else { - this.parent = true; - } - - // first create a new line - this.out.write('\n'); - - // indent the line - this.indentOutput(indent); - - // the element - this.out.write("<" + qName); - - int attrCount = atts.getLength(); - - for (int i = 0; i < attrCount; i++) { - //we need a white space between the - //attributes - this.indentOutput(1); - - String uri = atts.getURI(i); - String qname = atts.getQName(i); - - // if (uri.length() > 0) { - // String prefix = qname.substring(0, qname.indexOf(':')); - // out - // .write(" xmlns:" + prefix + "=\"" + uri - // + "\" "); - // } - String value = atts.getValue(i); - if(value == null){ - value=""; - } - this.out.write(qname + "=\"" + encodeXML(atts.getValue(i)) + - "\""); - } - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - // no text in this context now - this.textContentList.add(Boolean.valueOf(false)); - } - - public void startPrefixMapping(String prefix, String uri) - throws SAXException { - } - - /** - * Indent the output - * - * @param indentSize - */ - private void indentOutput(int indentSize) { - try { - for (int i = 0; i < indentSize; i++) { - this.out.write(' '); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - public static String encodeXML(String text) { - int length = text.length(); - StringBuffer work = new StringBuffer(length); - - for (int i = 0; i < length; i++) { - char c = text.charAt(i); - - if (c == '&') { - work.append("&"); - } else if (c == '<') { - work.append("<"); - } else if (c == '>') { - work.append(">"); - } else if (!Character.isIdentifierIgnorable(c)) { - work.append(c); - } - } - - return work.toString(); - } - - public void setDTD(String dtd) { - this.dtd = dtd; - } - - protected void queryXMLNS(Attributes atts) { - for (int i = 0; i < atts.getLength(); i++) { - String qname = atts.getQName(i); - - if (qname.startsWith("xmlns:")) { - String prefix = atts.getLocalName(i); - String uri = atts.getValue(i); - rootxmlns.put(uri, prefix); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.kabeja.xml.SAXSerializer#getMimeType() - */ - public String getMimeType() { - return MIMETYPE; - } - - /* - * (non-Javadoc) - * - * @see org.kabeja.xml.SAXSerializer#getSuffix() - */ - public String getSuffix() { - if (gzip) { - return SUFFIX_GZIP; - } else { - return SUFFIX; - } - } - - /* - * (non-Javadoc) - * - * @see org.kabeja.xml.SAXSerializer#setOutput(java.io.OutputStream) - */ - public void setOutput(OutputStream out) { - OutputStream bout = null; - - try { - if (gzip) { - bout = new BufferedOutputStream(new GZIPOutputStream(out)); - } else { - bout = new BufferedOutputStream(out); - } - - this.out = new OutputStreamWriter(bout, this.encoding); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see org.kabeja.xml.SAXSerializer#setProperties(java.util.Map) - */ - public void setProperties(Map properties) { - this.properties = properties; - - if (properties.containsKey(PROPERTY_ENCODING)) { - this.encoding = (String) properties.get(PROPERTY_ENCODING); - } - - if (properties.containsKey(PROPERTY_GZIP)) { - this.gzip = Boolean.getBoolean((String) properties.get( - PROPERTY_GZIP)); - } - } +public class SAXPrettyOutputter extends AbstractSAXSerializer implements SAXSerializer { + + /** The Constant DEFAULT_ENCODING. */ + public static final String DEFAULT_ENCODING = "UTF-8"; + + /** The Constant SUFFIX. */ + public static final String SUFFIX = "svg"; + + /** The Constant SUFFIX_GZIP. */ + public static final String SUFFIX_GZIP = "svgz"; + + /** The Constant MIMETYPE. */ + public static final String MIMETYPE = "text/svg"; + + /** The Constant PROPERTY_ENCODING. */ + public static final String PROPERTY_ENCODING = "encoding"; + + /** The Constant PROPERTY_GZIP. */ + public static final String PROPERTY_GZIP = "gzip"; + + /** The out. */ + private OutputStreamWriter out; + + /** The encoding. */ + private String encoding; + + /** The dtd. */ + private String dtd; + + /** The indent. */ + private int indent = 0; + + /** The parent. */ + private boolean parent = false; + + /** The text content list. */ + private final ArrayList textContentList = new ArrayList<>(); + + /** The rootxmlns. */ + protected HashMap rootxmlns = new HashMap<>(); + + /** The gzip. */ + protected boolean gzip = false; + + /** + * Instantiates a new SAX pretty outputter. + * + * @param output + * the output + * @param encoding + * the encoding + */ + public SAXPrettyOutputter(final OutputStream output, final String encoding) { + this.encoding = encoding; + this.setOutput(output); + } + + /** + * + */ + public SAXPrettyOutputter(final OutputStream out) { + this(out, DEFAULT_ENCODING); + } + + /** + * Instantiates a new SAX pretty outputter. + */ + public SAXPrettyOutputter() { + this.encoding = DEFAULT_ENCODING; + } + + @Override + public void characters(final char[] ch, final int start, final int length) throws SAXException { + try { + if (length > 0) { + if (parent) { + this.out.write(">"); + parent = false; + } + + char[] enc = encodeXML(new String(ch, 0, length)).toCharArray(); + this.out.write(enc, start, enc.length); + + // textNode in this context + textContentList.set(textContentList.size() - 1, true); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void endDocument() throws SAXException { + try { + this.out.flush(); + this.out.close(); + + textContentList.clear(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException { + try { + if (parent) { + this.out.write("/>"); + } else { + // check for textNodes in this context + Boolean b = textContentList.remove(textContentList.size() - 1); + + if (b.booleanValue()) {} else { + // there was no textNode we can create a new line + this.out.write('\n'); + indentOutput(indent); + } + this.out.write(""); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + indent--; + parent = false; + } + + @Override + public void endPrefixMapping(final String prefix) throws SAXException {} + + @Override + public void ignorableWhitespace(final char[] ch, final int start, final int length) throws SAXException {} + + @Override + public void processingInstruction(final String target, final String data) throws SAXException {} + + @Override + public void setDocumentLocator(final Locator locator) {} + + @Override + public void skippedEntity(final String name) throws SAXException {} + + @Override + public void startDocument() throws SAXException { + indent = 0; + + try { + this.out.write(""); + + if (this.dtd != null) { this.out.write("\n"); } + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Override + public void startElement(final String namespaceURI, final String localName, final String qName, + final Attributes atts) throws SAXException { + this.indent++; + + try { + if (this.parent) { + // we are nested + this.out.write(">"); + } else { + this.parent = true; + } + + // first create a new line + this.out.write('\n'); + + // indent the line + this.indentOutput(indent); + + // the element + this.out.write("<" + qName); + + int attrCount = atts.getLength(); + + for (int i = 0; i < attrCount; i++) { + // we need a white space between the + // attributes + this.indentOutput(1); + + // String uri = atts.getURI(i); + String qname = atts.getQName(i); + + // if (uri.length() > 0) { + // String prefix = qname.substring(0, qname.indexOf(':')); + // out + // .write(" xmlns:" + prefix + "=\"" + uri + // + "\" "); + // } + String value = atts.getValue(i); + if (value == null) { value = ""; } + this.out.write(qname + "=\"" + encodeXML(atts.getValue(i)) + "\""); + } + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + // no text in this context now + this.textContentList.add(false); + } + + @Override + public void startPrefixMapping(final String prefix, final String uri) throws SAXException {} + + /** + * Indent the output + * + * @param indentSize + */ + private void indentOutput(final int indentSize) { + try { + for (int i = 0; i < indentSize; i++) { this.out.write(' '); } + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Encode XML. + * + * @param text + * the text + * @return the string + */ + public static String encodeXML(final String text) { + int length = text.length(); + StringBuilder work = new StringBuilder(length); + + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + case '&': + work.append("&"); + break; + case '<': + work.append("<"); + break; + case '>': + work.append(">"); + break; + default: + if (!Character.isIdentifierIgnorable(c)) { work.append(c); } + break; + } + } + + return work.toString(); + } + + /** + * Sets the dtd. + * + * @param dtd + * the new dtd + */ + public void setDTD(final String dtd) { this.dtd = dtd; } + + /** + * Query XMLNS. + * + * @param atts + * the atts + */ + protected void queryXMLNS(final Attributes atts) { + for (int i = 0; i < atts.getLength(); i++) { + String qname = atts.getQName(i); + + if (qname.startsWith("xmlns:")) { + String prefix = atts.getLocalName(i); + String uri = atts.getValue(i); + rootxmlns.put(uri, prefix); + } + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#getMimeType() + */ + @Override + public String getMimeType() { return MIMETYPE; } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#getSuffix() + */ + @Override + public String getSuffix() { + if (gzip) return SUFFIX_GZIP; + return SUFFIX; + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#setOutput(java.io.OutputStream) + */ + @Override + public void setOutput(final OutputStream out) { + OutputStream bout = null; + + try { + if (gzip) { + bout = new BufferedOutputStream(new GZIPOutputStream(out)); + } else { + bout = new BufferedOutputStream(out); + } + + this.out = new OutputStreamWriter(bout, this.encoding); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /* + * (non-Javadoc) + * + * @see org.kabeja.xml.SAXSerializer#setProperties(java.util.Map) + */ + @Override + public void setProperties(final Map properties) { + this.properties = properties; + + if (properties.containsKey(PROPERTY_ENCODING)) { this.encoding = (String) properties.get(PROPERTY_ENCODING); } + + if (properties.containsKey(PROPERTY_GZIP)) { + this.gzip = Boolean.getBoolean((String) properties.get(PROPERTY_GZIP)); + } + } } diff --git a/msi.gama.ext/src/msi/gama/ext/kml/Feature.java b/msi.gama.ext/src/msi/gama/ext/kml/Feature.java index a311a0be07..b8afe268aa 100644 --- a/msi.gama.ext/src/msi/gama/ext/kml/Feature.java +++ b/msi.gama.ext/src/msi/gama/ext/kml/Feature.java @@ -1,9 +1,20 @@ +/******************************************************************************************************* + * + * Feature.java, in msi.gama.ext, is part of the source code of the + * GAMA modeling and simulation platform (v.1.8.2). + * + * (c) 2007-2022 UMI 209 UMMISCO IRD/SU & Partners (IRIT, MIAT, TLU, CTU) + * + * Visit https://github.com/gama-platform/gama for license information and contacts. + * + ********************************************************************************************************/ package msi.gama.ext.kml; import java.util.ArrayList; import java.util.List; +import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -12,6 +23,7 @@ import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + import msi.gama.ext.kml.annotations.Obvious; import msi.gama.ext.kml.atom.Author; import msi.gama.ext.kml.atom.Link; @@ -22,16 +34,17 @@ import msi.gama.ext.kml.xal.Locality; import msi.gama.ext.kml.xal.Thoroughfare; - /** * *

- * This is an abstract element and cannot be used directly in a KML file. The following - * diagram shows how some of a Feature's elements appear in Google Earth. + * This is an abstract element and cannot be used directly in a KML file. The following diagram shows how some of a + * Feature's elements appear in Google Earth. *

- * - * Syntax: - *
<!-- abstract element; do not create -->
+ *
+ * Syntax:
+ *
+ * 
+ * <!-- abstract element; do not create -->
  * <!-- Feature id="ID" -->                <!-- Document,Folder,
  *                                              NetworkLink,Placemark,
  *                                              GroundOverlay,PhotoOverlay,ScreenOverlay -->
@@ -49,1813 +62,1540 @@
  *   <StyleSelector>...</StyleSelector>
  *   <Region>...</Region>
  *   <Metadata>...</Metadata>              <!-- deprecated in KML 2.2 -->
- *   <ExtendedData>...</ExtendedData>      <!-- new in KML 2.2 -->
<-- /Feature -->
- * - * Extends: + * <ExtendedData>...</ExtendedData> <!-- new in KML 2.2 -->
<-- /Feature --> + *
+ * + * Extends: + * * @see: - * - * Extended By: + * + * Extended By: * @see: * @see: * @see: * @see: * @see: - * - * - * + * + * + * */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "AbstractFeatureType", propOrder = { - "name", - "visibility", - "open", - "atomAuthor", - "atomLink", - "address", - "xalAddressDetails", - "phoneNumber", - "snippet", - "snippetd", - "description", - "abstractView", - "timePrimitive", - "styleUrl", - "styleSelector", - "region", - "metadata", - "extendedData", - "featureSimpleExtension", - "featureObjectExtension" -}) -@XmlSeeAlso({ - Tour.class, - Overlay.class, - NetworkLink.class, - Container.class, - Placemark.class -}) -public abstract class Feature - extends AbstractObject - implements Cloneable -{ - - /** - * - *

- * User-defined text displayed in the 3D viewer as the label for the object (for example, - * for a Placemark, Folder, or NetworkLink). - *

- * - * - * - */ - protected String name; - /** - * - *

- * Boolean value. Specifies whether the feature is drawn in the 3D viewer when it is - * initially loaded. In order for a feature to be visible, the tag of - * all its ancestors must also be set to 1. In the Google Earth List View, each Feature - * has a checkbox that allows the user to control visibility of the Feature. - *

- * - * - * - */ - @XmlElement(defaultValue = "1") - @XmlJavaTypeAdapter(BooleanConverter.class) - protected Boolean visibility; - /** - * - *

- * Boolean value. Specifies whether a Document or Folder appears closed or open when - * first loaded into the Places panel. 0=collapsed (the default), 1=expanded. See also - * . This element applies only to Document, Folder, and NetworkLink. - *

- * - * - * - */ - @XmlElement(defaultValue = "0") - @XmlJavaTypeAdapter(BooleanConverter.class) - protected Boolean open; - /** - * - *

- * KML 2.2 supports new elements for including data about the author and related website - * in your KML file. This information is displayed in geo search results, both in Earth - * browsers such as Google Earth, and in other applications such as Google Maps. The - * ascription elements used in KML are as follows: - *

- *

- * The element is the parent element for , which specifies - * the author of the KML feature. - *

- *

- * These elements are defined in the Atom Syndication Format. The complete specification - * is found at http://atompub.org. (see the sample that follows). - *

- *

- * These elements are defined in the Atom Syndication Format. The complete specification - * is found at http://atompub.org. (see the sample that follows). - *

- * - * - * - */ - @XmlElement(name = "author", namespace = "http://www.w3.org/2005/Atom") - protected Author atomAuthor; - /** - * (required). see . - *

- * specifies the location of any of the following: - *

- *

- * If the file specified in is a local file, the and - * elements are not used. - *

- *

- * KML files fetched by network links Image files used in any Overlay (the element - * specifies the image in an Overlay; has the same fields as ) Model files - * used in the element - *

- *

- * Specifies the URL of the website containing this KML or KMZ file. Be sure to include - * the namespace for this element in any KML file that uses it: xmlns:atom="http://www.w3.org/2005/Atom" - * (see the sample that follows). - *

- *

- * Specifies the file to load and optional refresh parameters. See . - *

- *

- * The element replaces the element of contained in earlier - * KML releases and adds functionality for the element (introduced in KML - * 2.1). In Google Earth releases 3.0 and earlier, the element is ignored. - *

- *

- * The file is conditionally loaded and refreshed, depending on the refresh parameters - * supplied here. Two different sets of refresh parameters can be specified: one set - * is based on time ( and ) and one is based on the current - * "camera" view ( and ). In addition, Link specifies - * whether to scale the bounding box parameters that are sent to the server ( - * and provides a set of optional viewing parameters that can be sent to the server - * () as well as a set of optional parameters containing version and language - * information. - *

- *

- * Tip: To display the top-level Folder or Document within a Network Link in the List - * View, assign an ID to the Folder or Document. Without this ID, only the child object - * names are displayed in the List View. - *

- *

- * When a file is fetched, the URL that is sent to the server is composed of three - * pieces of information: - *

- *

- * the href (Hypertext Reference) that specifies the file to load. an arbitrary format - * string that is created from (a) parameters that you specify in the - * element or (b) bounding box parameters (this is the default and is used if no - * element is included in the file). a second format string that is specified in the - * element. - *

- * - * Syntax: - *
<Link id="ID">
-     *   <!-- specific to Link -->
-     *   <href>...</href>                      <!-- string -->
-     *   <refreshMode>onChange</refreshMode>   
-     *     <!-- refreshModeEnum: onChange, onInterval, or onExpire -->   
-     *   <refreshInterval>4</refreshInterval>  <!-- float -->
-     *   <viewRefreshMode>never</viewRefreshMode> 
-     *     <!-- viewRefreshModeEnum: never, onStop, onRequest, onRegion -->
-     *   <viewRefreshTime>4</viewRefreshTime>  <!-- float -->
-     *   <viewBoundScale>1</viewBoundScale>    <!-- float -->
-     *   <viewFormat>BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]</viewFormat>
-     *                                         <!-- string -->
-     *   <httpQuery>...</httpQuery>            <!-- string -->
-     * </Link>
- * - * Extends: - * @see: - * - * Contained By: - * @see: - * @see: - * - * See Also: - * - * - * - * - * - */ - @XmlElement(name = "link", namespace = "http://www.w3.org/2005/Atom") - protected Link atomLink; - /** - *
- *

- * A string value representing an unstructured address written as a standard street, - * city, state address, and/or as a postal code. You can use the

tag to specify - * the location of a point instead of using latitude and longitude coordinates. (However, - * if a is provided, it takes precedence over the
.) To find out which - * locales are supported for this tag in Google Earth, go to the Google Maps Help. - *

- * - * - * - */ - protected String address; - /** - * - *

- * A structured address, formatted as xAL, or eXtensible Address Language, an international - * standard for address formatting. is used by KML for geocoding - * in Google Maps only. For details, see the Google Maps API documentation. Currently, - * Google Earth does not use this element; use

instead. Be sure to include - * the namespace for this element in any KML file that uses it: xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" - *

- *

- * A structured address, formatted as xAL, or eXtensible Address Language, an international - * standard for address formatting. is used by KML for geocoding - * in Google Maps only. For details, see the Google Maps API documentation. Currently, - * Google Earth does not use this element; use

instead. Be sure to include - * the namespace for this element in any KML file that uses it: xmlns:xal="urn:oasis:names:tc:ciq:xsdschema:xAL:2.0" - *

- * - * - * - */ - @XmlElement(name = "AddressDetails", namespace = "urn:oasis:names:tc:ciq:xsdschema:xAL:2.0") - protected AddressDetails xalAddressDetails; - /** - * - * - * - */ - protected String phoneNumber; - /** - * - *

- * A short description of the feature. In Google Earth, this description is displayed - * in the Places panel under the name of the feature. If a Snippet is not supplied, - * the first two lines of the are used. In Google Earth, if a Placemark - * contains both a description and a Snippet, the appears beneath the Placemark - * in the Places panel, and the appears in the Placemark's description - * balloon. This tag does not support HTML markup. has a maxLines attribute, - * an integer that specifies the maximum number of lines to display. - *

- * - * - * - */ - @XmlElement(name = "Snippet") - protected Snippet snippet; - @XmlElement(name = "snippet") - protected String snippetd; - /** - * - *

- * The supported content for the element changed from Google Earth 4.3 - * to 5.0. Specific information for each version is listed out below, followed by information - * common to both. - *

- *

- * User-supplied content that appears in the description balloon. - *

- *

- * User-supplied content that appears in the description balloon. The supported content - * for the element changed from Google Earth 4.3 to 5.0. Specific information - * for each version is listed out below, followed by information common to both. Google - * Earth 5.0 Google Earth 5.0 supports plain text content, as well as full HTML and - * JavaScript, within description balloons. Contents of the description tag are rendered - * by the WebKit open source web browser engine, and are displayed as they would be - * in any WebKit-based browser. General restrictions Links to local files are generally - * not allowed. This prevents malicious code from damaging your system or accessing - * your data. Should you wish to allow access to your local filesystem, select Preferences - * > Allow placemark balloons to access local files and personal data. Links to image - * files on the local filesystem are always allowed, if contained within an tag. - * Content that has been compressed into a KMZ file can be accessed, even if on the - * local filesystem. Cookies are completely disabled, including cookies set or read - * by content contained within a iFrame. There are no exceptions to this rule. Doctype - * declarations are ignored. - *

- * - * - * - */ - protected String description; - /** - * - *

- * Defines a viewpoint associated with any element derived from Feature. See - * and . - *

- *

- * This is an abstract element and cannot be used directly in a KML file. This element - * is extended by the and elements. - *

- * - * Syntax: - *
<!-- abstract element; do not create -->
-     * <!-- AbstractView -->                   <!-- Camera, LookAt -->                
-     *   <!-- extends Object -->
-     *   <TimePrimitive>...</TimePrimitive>                        <!-- gx:TimeSpan or gx:TimeStamp -->
-     * <-- /AbstractView -->
- * - * Extends: - * @see: - * - * Extended By: - * @see: - * @see: - * - * - * - */ - @XmlElementRef(name = "AbstractViewGroup", namespace = "http://www.opengis.net/kml/2.2", required = false) - protected AbstractView abstractView; - /** - * - *

- * Associates this Feature with a period of time () or a point in time (). - *

- *

- * This is an abstract element and cannot be used directly in a KML file. This element - * is extended by the and elements. - *

- * - * Syntax: - *
<!-- abstract element; do not create -->
-     * <!-- TimePrimitive id="ID" -->            <!-- TimeSpan,TimeStamp -->               
-     *   <!-- extends Object -->
-     * <!-- /TimePrimitive -->
- * - * Extends: - * @see: - * - * Extended By: - * @see: - * @see: - * - * - * - */ - @XmlElementRef(name = "AbstractTimePrimitiveGroup", namespace = "http://www.opengis.net/kml/2.2", required = false) - protected TimePrimitive timePrimitive; - /** - * - *

- * URL of a