repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
z3
z3-master/src/api/java/StatisticsDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: StatisticsDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class StatisticsDecRefQueue extends IDecRefQueue<Statistics> { public StatisticsDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.statsDecRef(ctx.nCtx(), obj); } }
470
14.193548
62
java
z3
z3-master/src/api/java/Status.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Status.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Status values. **/ public enum Status { // / Used to signify an unsatisfiable status. UNSATISFIABLE(-1), // / Used to signify an unknown status. UNKNOWN(0), // / Used to signify a satisfiable status. SATISFIABLE(1); private final int intValue; Status(int v) { this.intValue = v; } public static Status fromInt(int v) { for (Status k : values()) if (k.intValue == v) return k; return values()[0]; } public final int toInt() { return this.intValue; } }
797
13.777778
56
java
z3
z3-master/src/api/java/StringSymbol.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: StringSymbol.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_symbol_kind; /** * Named symbols **/ public class StringSymbol extends Symbol { /** * The string value of the symbol. * Remarks: Throws an exception if the * symbol is not of string kind. **/ public String getString() { return Native.getSymbolString(getContext().nCtx(), getNativeObject()); } StringSymbol(Context ctx, long obj) { super(ctx, obj); } StringSymbol(Context ctx, String s) { super(ctx, Native.mkStringSymbol(ctx.nCtx(), s)); } @Override void checkNativeObject(long obj) { if (Native.getSymbolKind(getContext().nCtx(), obj) != Z3_symbol_kind.Z3_STRING_SYMBOL .toInt()) { throw new Z3Exception("Symbol is not of String kind"); } super.checkNativeObject(obj); } }
1,086
18.070175
93
java
z3
z3-master/src/api/java/Symbol.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Symbol.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; import com.microsoft.z3.enumerations.Z3_symbol_kind; /** * Symbols are used to name several term and type constructors. **/ public class Symbol extends Z3Object { /** * The kind of the symbol (int or string) **/ protected Z3_symbol_kind getKind() { return Z3_symbol_kind.fromInt(Native.getSymbolKind(getContext().nCtx(), getNativeObject())); } /** * Indicates whether the symbol is of Int kind **/ public boolean isIntSymbol() { return getKind() == Z3_symbol_kind.Z3_INT_SYMBOL; } /** * Indicates whether the symbol is of string kind. **/ public boolean isStringSymbol() { return getKind() == Z3_symbol_kind.Z3_STRING_SYMBOL; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Symbol)) return false; Symbol other = (Symbol) o; return this.getNativeObject() == other.getNativeObject(); } /** * A string representation of the symbol. **/ @Override public String toString() { if (isIntSymbol()) { return Integer.toString(((IntSymbol) this).getInt()); } else if (isStringSymbol()) { return ((StringSymbol) this).getString(); } else { return "Z3Exception: Unknown symbol kind encountered."; } } /** * Symbol constructor **/ protected Symbol(Context ctx, long obj) { super(ctx, obj); } @Override void incRef() { // Symbol does not require tracking. } @Override void addToReferenceQueue() { // Symbol does not require tracking. } static Symbol create(Context ctx, long obj) { switch (Z3_symbol_kind.fromInt(Native.getSymbolKind(ctx.nCtx(), obj))) { case Z3_INT_SYMBOL: return new IntSymbol(ctx, obj); case Z3_STRING_SYMBOL: return new StringSymbol(ctx, obj); default: throw new Z3Exception("Unknown symbol kind encountered"); } } }
2,317
20.867925
79
java
z3
z3-master/src/api/java/Tactic.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Tactic.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Tactics are the basic building block for creating custom solvers for specific * problem domains. The complete list of tactics may be obtained using * {@code Context.NumTactics} and {@code Context.TacticNames}. It may * also be obtained using the command {@code (help-tactic)} in the SMT 2.0 * front-end. **/ public class Tactic extends Z3Object { /** * A string containing a description of parameters accepted by the tactic. **/ public String getHelp() { return Native.tacticGetHelp(getContext().nCtx(), getNativeObject()); } /** * Retrieves parameter descriptions for Tactics. * @throws Z3Exception **/ public ParamDescrs getParameterDescriptions() { return new ParamDescrs(getContext(), Native.tacticGetParamDescrs(getContext() .nCtx(), getNativeObject())); } /** * Execute the tactic over the goal. * @throws Z3Exception **/ public ApplyResult apply(Goal g) { return apply(g, null); } /** * Execute the tactic over the goal. * @throws Z3Exception **/ public ApplyResult apply(Goal g, Params p) { getContext().checkContextMatch(g); if (p == null) return new ApplyResult(getContext(), Native.tacticApply(getContext() .nCtx(), getNativeObject(), g.getNativeObject())); else { getContext().checkContextMatch(p); return new ApplyResult(getContext(), Native.tacticApplyEx(getContext().nCtx(), getNativeObject(), g.getNativeObject(), p.getNativeObject())); } } /** * Creates a solver that is implemented using the given tactic. * @see Context#mkSolver(Tactic) * @throws Z3Exception **/ public Solver getSolver() { return getContext().mkSolver(this); } Tactic(Context ctx, long obj) { super(ctx, obj); } Tactic(Context ctx, String name) { super(ctx, Native.mkTactic(ctx.nCtx(), name)); } @Override void incRef() { Native.tacticIncRef(getContext().nCtx(), getNativeObject()); } @Override void addToReferenceQueue() { getContext().getTacticDRQ().storeReference(getContext(), this); } }
2,543
23.461538
85
java
z3
z3-master/src/api/java/TacticDecRefQueue.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: TacticDecRefQueue.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; class TacticDecRefQueue extends IDecRefQueue<Tactic> { public TacticDecRefQueue() { super(); } @Override protected void decRef(Context ctx, long obj) { Native.tacticDecRef(ctx.nCtx(), obj); } }
459
13.375
56
java
z3
z3-master/src/api/java/TupleSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: TupleSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Tuple sorts. **/ public class TupleSort extends Sort { /** * The constructor function of the tuple. * @throws Z3Exception **/ public FuncDecl<TupleSort> mkDecl() { return new FuncDecl<>(getContext(), Native.getTupleSortMkDecl(getContext() .nCtx(), getNativeObject())); } /** * The number of fields in the tuple. **/ public int getNumFields() { return Native.getTupleSortNumFields(getContext().nCtx(), getNativeObject()); } /** * The field declarations. * @throws Z3Exception **/ public FuncDecl<?>[] getFieldDecls() { int n = getNumFields(); FuncDecl<?>[] res = new FuncDecl[n]; for (int i = 0; i < n; i++) res[i] = new FuncDecl<>(getContext(), Native.getTupleSortFieldDecl( getContext().nCtx(), getNativeObject(), i)); return res; } TupleSort(Context ctx, Symbol name, int numFields, Symbol[] fieldNames, Sort[] fieldSorts) { super(ctx, Native.mkTupleSort(ctx.nCtx(), name.getNativeObject(), numFields, Symbol.arrayToNative(fieldNames), AST.arrayToNative(fieldSorts), new Native.LongPtr(), new long[numFields])); } };
1,509
21.205882
84
java
z3
z3-master/src/api/java/UninterpretedSort.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: UninterpretedSort.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Uninterpreted Sorts **/ public class UninterpretedSort extends Sort { UninterpretedSort(Context ctx, long obj) { super(ctx, obj); } UninterpretedSort(Context ctx, Symbol s) { super(ctx, Native.mkUninterpretedSort(ctx.nCtx(), s.getNativeObject())); } }
520
13.885714
80
java
z3
z3-master/src/api/java/UserPropagatorBase.java
package com.microsoft.z3; import com.microsoft.z3.Context; import com.microsoft.z3.enumerations.Z3_lbool; public abstract class UserPropagatorBase extends Native.UserPropagatorBase { private Context ctx; private Solver solver; public UserPropagatorBase(Context _ctx, Solver _solver) { super(_ctx.nCtx(), _solver.getNativeObject()); ctx = _ctx; solver = _solver; } public final Context getCtx() { return ctx; } public final Solver getSolver() { return solver; } @Override protected final void pushWrapper() { push(); } @Override protected final void popWrapper(int number) { pop(number); } @Override protected final void finWrapper() { fin(); } @Override protected final void eqWrapper(long lx, long ly) { Expr x = new Expr(ctx, lx); Expr y = new Expr(ctx, ly); eq(x, y); } @Override protected final UserPropagatorBase freshWrapper(long lctx) { return fresh(new Context(lctx)); } @Override protected final void createdWrapper(long last) { created(new Expr(ctx, last)); } @Override protected final void fixedWrapper(long lvar, long lvalue) { Expr var = new Expr(ctx, lvar); Expr value = new Expr(ctx, lvalue); fixed(var, value); } public abstract void push(); public abstract void pop(int number); public abstract UserPropagatorBase fresh(Context ctx); public <R extends Sort> void created(Expr<R> ast) {} public <R extends Sort> void fixed(Expr<R> var, Expr<R> value) {} public <R extends Sort> void eq(Expr<R> x, Expr<R> y) {} public void fin() {} public final <R extends Sort> void add(Expr<R> expr) { Native.propagateAdd(this, ctx.nCtx(), solver.getNativeObject(), javainfo, expr.getNativeObject()); } public final <R extends Sort> void conflict(Expr<R>[] fixed) { conflict(fixed, new Expr[0], new Expr[0]); } public final <R extends Sort> void conflict(Expr<R>[] fixed, Expr<R>[] lhs, Expr<R>[] rhs) { AST conseq = ctx.mkBool(false); Native.propagateConflict( this, ctx.nCtx(), solver.getNativeObject(), javainfo, fixed.length, AST.arrayToNative(fixed), lhs.length, AST.arrayToNative(lhs), AST.arrayToNative(rhs), conseq.getNativeObject()); } public final <R extends Sort> boolean nextSplit(Expr<R> e, long idx, Z3_lbool phase) { return Native.propagateNextSplit( this, ctx.nCtx(), solver.getNativeObject(), javainfo, e.getNativeObject(), idx, phase.toInt()); } }
2,686
26.418367
138
java
z3
z3-master/src/api/java/Version.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Version.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Version information. * Remarks: Note that this class is static. **/ public class Version { /** * The major version **/ public static int getMajor() { Native.IntPtr major = new Native.IntPtr(), minor = new Native.IntPtr(), build = new Native.IntPtr(), revision = new Native.IntPtr(); Native.getVersion(major, minor, build, revision); return major.value; } /** * The minor version **/ public static int getMinor() { Native.IntPtr major = new Native.IntPtr(), minor = new Native.IntPtr(), build = new Native.IntPtr(), revision = new Native.IntPtr(); Native.getVersion(major, minor, build, revision); return minor.value; } /** * The build version **/ public static int getBuild() { Native.IntPtr major = new Native.IntPtr(), minor = new Native.IntPtr(), build = new Native.IntPtr(), revision = new Native.IntPtr(); Native.getVersion(major, minor, build, revision); return build.value; } /** * The revision **/ public static int getRevision() { Native.IntPtr major = new Native.IntPtr(), minor = new Native.IntPtr(), build = new Native.IntPtr(), revision = new Native.IntPtr(); Native.getVersion(major, minor, build, revision); return revision.value; } /** * A full version string **/ public static String getFullVersion() { return Native.getFullVersion(); } /** * A string representation of the version information. **/ public static String getString() { Native.IntPtr major = new Native.IntPtr(), minor = new Native.IntPtr(), build = new Native.IntPtr(), revision = new Native.IntPtr(); Native.getVersion(major, minor, build, revision); return Integer.toString(major.value) + "." + Integer.toString(minor.value) + "." + Integer.toString(build.value) + "." + Integer.toString(revision.value); } }
2,221
25.141176
140
java
z3
z3-master/src/api/java/Z3Exception.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Z3Exception.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * The exception base class for error reporting from Z3 **/ @SuppressWarnings("serial") public class Z3Exception extends RuntimeException { /** * Constructor. **/ public Z3Exception() { super(); } /** * Constructor. **/ public Z3Exception(String message) { super(message); } /** * Constructor. **/ public Z3Exception(String message, Exception inner) { super(message, inner); } }
702
12.784314
56
java
z3
z3-master/src/api/java/Z3Object.java
/** Copyright (c) 2012-2014 Microsoft Corporation Module Name: Z3Object.java Abstract: Author: @author Christoph Wintersteiger (cwinter) 2012-03-15 Notes: **/ package com.microsoft.z3; /** * Internal base class for interfacing with native Z3 objects. Should not be * used externally. **/ public abstract class Z3Object { private final Context m_ctx; private final long m_n_obj; Z3Object(Context ctx, long obj) { m_ctx = ctx; checkNativeObject(obj); m_n_obj = obj; incRef(); addToReferenceQueue(); } /** * Add to ReferenceQueue for tracking reachability on the object and * decreasing the reference count when the object is no longer reachable. */ abstract void addToReferenceQueue(); /** * Increment reference count on {@code this}. */ abstract void incRef(); /** * This function is provided for overriding, and a child class * can insert consistency checks on {@code obj}. * * @param obj Z3 native object. */ void checkNativeObject(long obj) {} long getNativeObject() { return m_n_obj; } static long getNativeObject(Z3Object s) { if (s == null) return 0; return s.getNativeObject(); } Context getContext() { return m_ctx; } public static long[] arrayToNative(Z3Object[] a) { if (a == null) return null; long[] an = new long[a.length]; for (int i = 0; i < a.length; i++) an[i] = (a[i] == null) ? 0 : a[i].getNativeObject(); return an; } public static int arrayLength(Z3Object[] a) { return (a == null) ? 0 : a.length; } }
1,758
18.988636
77
java
cloc
cloc-master/tests/inputs/Java.java
// from http://www.roesler-ac.de/wolfram/hello.htm // Hello World in Java // 2016-12-02: additional code by https://github.com/filippucher1 // to test /* within quoted string github issue #140 @Controller @RequestMapping( "/path/*" ) public class ControllerClass { /** * javadoc * style */ /* block comment 1 - on one line */ /* block comment 2 */ /* * block comment 3 */ import java.io.*; class HelloWorld { static public void main( String args[] ) { System.out.println( "Hello World!" ); } }
514
15.612903
66
java
cloc
cloc-master/tests/inputs/hello.java
/* hello.java */ import java.io.*; class Hi { static public void main( String args[] ) { System.out.println( "Hello World!" ); /* insert comment here */ } }
256
24.7
65
java
cloc
cloc-master/tests/inputs/diff/A/d2/hello.java
/* hello.java */ import java.io.*; class Hi { static public void main( String args[] ) { System.out.println( "another line" ); System.out.println( "Hello World!" ); /* insert comment here */ } /* inline */ }
313
25.166667
65
java
cloc
cloc-master/tests/inputs/issues/365/RSpecTests.java
/* * https://raw.githubusercontent.com/elastic/logstash/master/x-pack/src/test/java/org/logstash/xpack/test/RSpecTests.java */ package org.logstash.xpack.test; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import org.jruby.runtime.builtin.IRubyObject; import org.junit.Assert; import org.junit.Test; import org.logstash.RubyUtil; import org.logstash.Rubyfier; public final class RSpecTests { @Test public void rspecTests() throws Exception { RubyUtil.RUBY.getENV().put("IS_JUNIT_RUN", "true"); RubyUtil.RUBY.getGlobalVariables().set( "$JUNIT_ARGV", Rubyfier.deep(RubyUtil.RUBY, Arrays.asList( "-fd", "--pattern", "spec/**/*_spec.rb" )) ); final Path rspec = Paths.get( org.assertj.core.util.Files.currentFolder().getParent(), "lib/bootstrap/rspec.rb" ); final IRubyObject result = RubyUtil.RUBY.executeScript( new String(Files.readAllBytes(rspec), StandardCharsets.UTF_8), rspec.toFile().getAbsolutePath() ); if (!result.toJava(Long.class).equals(0L)) { Assert.fail("RSpec test suit saw at least one failure."); } } }
1,298
33.184211
121
java
cloc
cloc-master/tests/inputs/issues/381/issue381.java
package com.triplemedia.sms.alphabets.cimd2; /** * Utility class for CIMD2 alphabet as defined in CIMD_Interface_Specification_SC70.pdf */ public class CIMD2Alphabet{ public static final char CIMD2_SPECIAL_COMBINATION_CHARACTER = '_'; public static final String COMMERCIAL_AT = "_Oa"; public static final String SMALL_LETTER_y = "y"; public static final String SMALL_LETTER_z = "z"; public static final String VERTICAL_BAR = "_XX_!!"; // | public static final String CARET = "_XX_gl"; // ^ public static final String EURO = "_XXe"; // public static final String OPENING_BRACE = "_XX("; // { public static final String CLOSING_BRACE = "_XX)"; // } public static final String PAGE_BREAK = "_XX\f)"; public static final String OPENING_BRACKET = "_XX<"; // [ public static final String CLOSING_BRACKET = "_XX>"; // ] public static final String TILDE = "_XX="; // ~ public static final String BACKSLASH = "_XX/"; // \ public static final String VERTICAL_BAR_NO_ESC = "_!!"; // | public static final String CARET_NO_ESC = "_gl"; // ^ public static final String EURO_NO_ESC = "e"; // public static final String OPENING_BRACE_NO_ESC = "("; // { public static final String CLOSING_BRACE_NO_ESC = ")"; // } public static final String PAGE_BREAK_NO_ESC = "\f"; public static final String OPENING_BRACKET_NO_ESC = "<"; // [ public static final String CLOSING_BRACKET_NO_ESC = ">"; // ] public static final String TILDE_NO_ESC = "="; // ~ public static final String BACKSLASH_NO_ESC = "/"; // \ }
1,596
43.361111
87
java
cloc
cloc-master/tests/inputs/issues/407/count_dir/Test/Java.java
// from http://www.roesler-ac.de/wolfram/hello.htm // Hello World in Java // 2016-12-02: additional code by https://github.com/filippucher1 // to test /* within quoted string github issue #140 @Controller @RequestMapping( "/path/*" ) public class ControllerClass { /** * javadoc * style */ /* block comment 1 - on one line */ /* block comment 2 */ /* * block comment 3 */ import java.io.*; class HelloWorld { static public void main( String args[] ) { System.out.println( "Hello World!" ); } }
514
15.612903
66
java
cloc
cloc-master/tests/inputs/issues/407/level2/Java.java
// from http://www.roesler-ac.de/wolfram/hello.htm // Hello World in Java // 2016-12-02: additional code by https://github.com/filippucher1 // to test /* within quoted string github issue #140 @Controller @RequestMapping( "/path/*" ) public class ControllerClass { /** * javadoc * style */ /* block comment 1 - on one line */ /* block comment 2 */ /* * block comment 3 */ import java.io.*; class HelloWorld { static public void main( String args[] ) { System.out.println( "Hello World!" ); } }
514
15.612903
66
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiAnimBehavior.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Defines how an animation channel behaves outside the defined time range. */ public enum AiAnimBehavior { /** * The value from the default node transformation is taken. */ DEFAULT(0x0), /** * The nearest key value is used without interpolation. */ CONSTANT(0x1), /** * The value of the nearest two keys is linearly extrapolated for the * current time value. */ LINEAR(0x2), /** * The animation is repeated.<p> * * If the animation key go from n to m and the current time is t, use the * value at (t-n) % (|m-n|). */ REPEAT(0x3); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiAnimBehavior fromRawValue(int rawValue) { for (AiAnimBehavior type : AiAnimBehavior.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiAnimBehavior(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
3,486
29.858407
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiAnimation.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.util.ArrayList; import java.util.List; /** * An animation.<p> * * An animation consists of keyframe data for a number of nodes. For * each node affected by the animation a separate series of data is given.<p> * * Like {@link AiMesh}, the animation related classes offer a Buffer API, a * Direct API and a wrapped API. Please consult the documentation of * {@link AiMesh} for a description and comparison of these APIs. */ public final class AiAnimation { /** * Name. */ private final String m_name; /** * Duration. */ private final double m_duration; /** * Ticks per second. */ private final double m_ticksPerSecond; /** * Bone animation channels. */ private final List<AiNodeAnim> m_nodeAnims = new ArrayList<AiNodeAnim>(); /** * Constructor. * * @param name name * @param duration duration * @param ticksPerSecond ticks per second */ AiAnimation(String name, double duration, double ticksPerSecond) { m_name = name; m_duration = duration; m_ticksPerSecond = ticksPerSecond; } /** * Returns the name of the animation.<p> * * If the modeling package this data was exported from does support only * a single animation channel, this name is usually empty (length is zero). * * @return the name */ public String getName() { return m_name; } /** * Returns the duration of the animation in ticks. * * @return the duration */ public double getDuration() { return m_duration; } /** * Returns the ticks per second.<p> * * 0 if not specified in the imported file * * @return the number of ticks per second */ public double getTicksPerSecond() { return m_ticksPerSecond; } /** * Returns the number of bone animation channels.<p> * * Each channel affects a single node. This method will return the same * value as <code>getChannels().size()</code> * * @return the number of bone animation channels */ public int getNumChannels() { return m_nodeAnims.size(); } /** * Returns the list of bone animation channels.<p> * * Each channel affects a single node. The array is mNumChannels in size. * * @return the list of bone animation channels */ public List<AiNodeAnim> getChannels() { return m_nodeAnims; } /** * Returns the number of mesh animation channels.<p> * * Each channel affects a single mesh and defines vertex-based animation. * This method will return the same value as * <code>getMeshChannels().size()</code> * * @return the number of mesh animation channels */ public int getNumMeshChannels() { throw new UnsupportedOperationException("not implemented yet"); } /** * Returns the list of mesh animation channels.<p> * * Each channel affects a single mesh. * * @return the list of mesh animation channels */ public List<AiMeshAnim> getMeshChannels() { throw new UnsupportedOperationException("not implemented yet"); } }
5,176
28.414773
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiBlendMode.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Defines alpha-blend flags.<p> * * If you're familiar with OpenGL or D3D, these flags aren't new to you. * They define *how* the final color value of a pixel is computed, basing * on the previous color at that pixel and the new color value from the * material. The blend formula is: * <br><code> * SourceColor * SourceBlend + DestColor * DestBlend * </code><br> * where <code>DestColor</code> is the previous color in the framebuffer at * this position and <code>SourceColor</code> is the material color before the * transparency calculation. */ public enum AiBlendMode { /** * Default blending.<p> * * Formula: * <code> * SourceColor*SourceAlpha + DestColor*(1-SourceAlpha) * </code> */ DEFAULT(0x0), /** * Additive blending.<p> * * Formula: * <code> * SourceColor*1 + DestColor*1 * </code> */ ADDITIVE(0x1); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiBlendMode fromRawValue(int rawValue) { for (AiBlendMode type : AiBlendMode.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiBlendMode(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
3,693
30.305085
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiBone.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.util.ArrayList; import java.util.List; /** * A single bone of a mesh.<p> * * A bone has a name by which it can be found in the frame hierarchy and by * which it can be addressed by animations. In addition it has a number of * influences on vertices.<p> * * This class is designed to be mutable, i.e., the returned collections are * writable and may be modified. */ public final class AiBone { /** * Name of the bone. */ private String m_name; /** * Bone weights. */ private final List<AiBoneWeight> m_boneWeights = new ArrayList<AiBoneWeight>(); /** * Offset matrix. */ private Object m_offsetMatrix; /** * Constructor. */ AiBone() { /* nothing to do */ } /** * Returns the name of the bone. * * @return the name */ public String getName() { return m_name; } /** * Returns the number of bone weights.<p> * * This method exists for compatibility with the native assimp API. * The returned value is identical to <code>getBoneWeights().size()</code> * * @return the number of weights */ public int getNumWeights() { return m_boneWeights.size(); } /** * Returns a list of bone weights. * * @return the bone weights */ public List<AiBoneWeight> getBoneWeights() { return m_boneWeights; } /** * Returns the offset matrix.<p> * * The offset matrix is a 4x4 matrix that transforms from mesh space to * bone space in bind pose.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers). * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the offset matrix */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> M4 getOffsetMatrix( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (M4) m_offsetMatrix; } }
3,976
28.029197
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiBoneWeight.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * A single influence of a bone on a vertex. */ public final class AiBoneWeight { /** * Constructor. */ AiBoneWeight() { /* nothing to do */ } /** * Index of the vertex which is influenced by the bone. * * @return the vertex index */ public int getVertexId() { return m_vertexId; } /** * The strength of the influence in the range (0...1).<p> * * The influence from all bones at one vertex amounts to 1 * * @return the influence */ public float getWeight() { return m_weight; } /** * Vertex index. */ private int m_vertexId; /** * Influence of bone on vertex. */ private float m_weight; }
2,639
28.662921
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiBuiltInWrapperProvider.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; /** * Wrapper provider using jassimp built in types. */ public final class AiBuiltInWrapperProvider implements AiWrapperProvider< AiVector, AiMatrix4f, AiColor, AiNode, AiQuaternion> { @Override public AiVector wrapVector3f(ByteBuffer buffer, int offset, int numComponents) { return new AiVector(buffer, offset, numComponents); } @Override public AiMatrix4f wrapMatrix4f(float[] data) { return new AiMatrix4f(data); } @Override public AiColor wrapColor(ByteBuffer buffer, int offset) { return new AiColor(buffer, offset); } @Override public AiNode wrapSceneNode(Object parent, Object matrix, int[] meshReferences, String name) { return new AiNode((AiNode) parent, matrix, meshReferences, name); } @Override public AiQuaternion wrapQuaternion(ByteBuffer buffer, int offset) { return new AiQuaternion(buffer, offset); } }
2,861
32.670588
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiCamera.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Helper structure to describe a virtual camera.<p> * * Cameras have a representation in the node graph and can be animated. * An important aspect is that the camera itself is also part of the * scenegraph. This means, any values such as the look-at vector are not * *absolute*, they're <b>relative</b> to the coordinate system defined * by the node which corresponds to the camera. This allows for camera * animations. For static cameras parameters like the 'look-at' or 'up' vectors * are usually specified directly in aiCamera, but beware, they could also * be encoded in the node transformation. The following (pseudo)code sample * shows how to do it: <p> * <code><pre> * // Get the camera matrix for a camera at a specific time * // if the node hierarchy for the camera does not contain * // at least one animated node this is a static computation * get-camera-matrix (node sceneRoot, camera cam) : matrix * { * node cnd = find-node-for-camera(cam) * matrix cmt = identity() * * // as usual - get the absolute camera transformation for this frame * for each node nd in hierarchy from sceneRoot to cnd * matrix cur * if (is-animated(nd)) * cur = eval-animation(nd) * else cur = nd->mTransformation; * cmt = mult-matrices( cmt, cur ) * end for * * // now multiply with the camera's own local transform * cam = mult-matrices (cam, get-camera-matrix(cmt) ) * } * </pre></code> * * <b>Note:</b> some file formats (such as 3DS, ASE) export a "target point" - * the point the camera is looking at (it can even be animated). Assimp * writes the target point as a subnode of the camera's main node, * called "<camName>.Target". However this is just additional information * then the transformation tracks of the camera main node make the * camera already look in the right direction. */ public final class AiCamera { /** * Constructor. * * @param name name * @param position position * @param up up vector * @param lookAt look-at vector * @param horizontalFOV field of view * @param clipNear near clip plane * @param clipFar far clip plane * @param aspect aspect ratio */ AiCamera(String name, Object position, Object up, Object lookAt, float horizontalFOV, float clipNear, float clipFar, float aspect) { m_name = name; m_position = position; m_up = up; m_lookAt = lookAt; m_horizontalFOV = horizontalFOV; m_clipNear = clipNear; m_clipFar = clipFar; m_aspect = aspect; } /** * Returns the name of the camera.<p> * * There must be a node in the scenegraph with the same name. * This node specifies the position of the camera in the scene * hierarchy and can be animated. */ public String getName() { return m_name; } /** * Returns the position of the camera.<p> * * The returned position is relative to the coordinate space defined by the * corresponding node.<p> * * The default value is 0|0|0.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the position vector */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getPosition(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_position; } /** * Returns the 'Up' - vector of the camera coordinate system. * * The returned vector is relative to the coordinate space defined by the * corresponding node.<p> * * The 'right' vector of the camera coordinate system is the cross product * of the up and lookAt vectors. The default value is 0|1|0. The vector * may be normalized, but it needn't.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the 'Up' vector */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getUp(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_up; } /** * Returns the 'LookAt' - vector of the camera coordinate system.<p> * * The returned vector is relative to the coordinate space defined by the * corresponding node.<p> * * This is the viewing direction of the user. The default value is 0|0|1. * The vector may be normalized, but it needn't.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the 'LookAt' vector */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getLookAt(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_lookAt; } /** * Returns the half horizontal field of view angle, in radians.<p> * * The field of view angle is the angle between the center line of the * screen and the left or right border. The default value is 1/4PI. * * @return the half horizontal field of view angle */ public float getHorizontalFOV() { return m_horizontalFOV; } /** * Returns the distance of the near clipping plane from the camera.<p> * * The value may not be 0.f (for arithmetic reasons to prevent a division * through zero). The default value is 0.1f. * * @return the distance of the near clipping plane */ public float getClipPlaneNear() { return m_clipNear; } /** * Returns the distance of the far clipping plane from the camera.<p> * * The far clipping plane must, of course, be further away than the * near clipping plane. The default value is 1000.0f. The ratio * between the near and the far plane should not be too * large (between 1000-10000 should be ok) to avoid floating-point * inaccuracies which could lead to z-fighting. * * @return the distance of the far clipping plane */ public float getClipPlaneFar() { return m_clipFar; } /** * Returns the screen aspect ratio.<p> * * This is the ration between the width and the height of the * screen. Typical values are 4/3, 1/2 or 1/1. This value is * 0 if the aspect ratio is not defined in the source file. * 0 is also the default value. * * @return the screen aspect ratio */ public float getAspect() { return m_aspect; } /** * Name. */ private final String m_name; /** * Position. */ private final Object m_position; /** * Up vector. */ private final Object m_up; /** * Look-At vector. */ private final Object m_lookAt; /** * FOV. */ private final float m_horizontalFOV; /** * Near clipping plane. */ private final float m_clipNear; /** * Far clipping plane. */ private final float m_clipFar; /** * Aspect ratio. */ private final float m_aspect; }
9,615
30.631579
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiClassLoaderIOSystem.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * IOSystem based on the Java classloader.<p> * * This IOSystem allows loading models directly from the * classpath. No extraction to the file system is * necessary. * * @author Jesper Smith * */ public class AiClassLoaderIOSystem implements AiIOSystem<AiInputStreamIOStream> { private final Class<?> clazz; private final ClassLoader classLoader; /** * Construct a new AiClassLoaderIOSystem.<p> * * This constructor uses a ClassLoader to resolve * resources. * * @param classLoader classLoader to resolve resources. */ public AiClassLoaderIOSystem(ClassLoader classLoader) { this.clazz = null; this.classLoader = classLoader; } /** * Construct a new AiClassLoaderIOSystem.<p> * * This constructor uses a Class to resolve * resources. * * @param class<?> class to resolve resources. */ public AiClassLoaderIOSystem(Class<?> clazz) { this.clazz = clazz; this.classLoader = null; } @Override public AiInputStreamIOStream open(String filename, String ioMode) { try { InputStream is; if(clazz != null) { is = clazz.getResourceAsStream(filename); } else if (classLoader != null) { is = classLoader.getResourceAsStream(filename); } else { System.err.println("[" + getClass().getSimpleName() + "] No class or classLoader provided to resolve " + filename); return null; } if(is != null) { return new AiInputStreamIOStream(is); } else { System.err.println("[" + getClass().getSimpleName() + "] Cannot find " + filename); return null; } } catch (IOException e) { e.printStackTrace(); return null; } } @Override public void close(AiInputStreamIOStream file) { } @Override public boolean exists(String path) { URL url = null; if(clazz != null) { url = clazz.getResource(path); } else if (classLoader != null) { url = classLoader.getResource(path); } if(url == null) { return false; } return true; } @Override public char getOsSeparator() { return '/'; } }
4,349
27.246753
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiColor.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; /** * Wrapper for colors.<p> * * The wrapper is writable, i.e., changes performed via the set-methods will * modify the underlying mesh. */ public final class AiColor { /** * Wrapped buffer. */ private final ByteBuffer m_buffer; /** * Offset into m_buffer. */ private final int m_offset; /** * Constructor. * * @param buffer the buffer to wrap * @param offset offset into buffer */ public AiColor(ByteBuffer buffer, int offset) { m_buffer = buffer; m_offset = offset; } /** * Returns the red color component. * * @return the red component */ public float getRed() { return m_buffer.getFloat(m_offset); } /** * Returns the green color component. * * @return the green component */ public float getGreen() { return m_buffer.getFloat(m_offset + 4); } /** * Returns the blue color component. * * @return the blue component */ public float getBlue() { return m_buffer.getFloat(m_offset + 8); } /** * Returns the alpha color component. * * @return the alpha component */ public float getAlpha() { return m_buffer.getFloat(m_offset + 12); } /** * Sets the red color component. * * @param red the new value */ public void setRed(float red) { m_buffer.putFloat(m_offset, red); } /** * Sets the green color component. * * @param green the new value */ public void setGreen(float green) { m_buffer.putFloat(m_offset + 4, green); } /** * Sets the blue color component. * * @param blue the new value */ public void setBlue(float blue) { m_buffer.putFloat(m_offset + 8, blue); } /** * Sets the alpha color component. * * @param alpha the new value */ public void setAlpha(float alpha) { m_buffer.putFloat(m_offset + 12, alpha); } @Override public String toString() { return "[" + getRed() + ", " + getGreen() + ", " + getBlue() + ", " + getAlpha() + "]"; } }
4,178
24.956522
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiConfig.java
/* * $Revision$ * $Date$ */ package jassimp; /** * Configuration interface for assimp importer.<p> * * This class is work-in-progress */ public class AiConfig { }
174
9.9375
50
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiConfigOptions.java
/* * $Revision$ * $Date$ */ package jassimp; /** * Lists all possible configuration options.<p> * * This class is work-in-progress */ public enum AiConfigOptions { /** * Maximum bone count per mesh for the SplitbyBoneCount step.<p> * * Meshes are split until the maximum number of bones is reached. The * default value is AI_SBBC_DEFAULT_MAX_BONES, which may be altered at * compile-time. This limit is imposed by the native jassimp library * and typically is 60.<p> * * Property data type: integer. */ PP_SBBC_MAX_BONES("PP_SBBC_MAX_BONES"), /** * Specifies the maximum angle that may be between two vertex tangents * that their tangents and bi-tangents are smoothed.<p> * * This applies to the CalcTangentSpace-Step. The angle is specified * in degrees. The maximum value is 175.<p> * * Property type: float. Default value: 45 degrees */ PP_CT_MAX_SMOOTHING_ANGLE("PP_CT_MAX_SMOOTHING_ANGLE"), /** * Source UV channel for tangent space computation.<p> * * The specified channel must exist or an error will be raised.<p> * * Property type: integer. Default value: 0 */ PP_CT_TEXTURE_CHANNEL_INDEX("PP_CT_TEXTURE_CHANNEL_INDEX"), /** * Specifies the maximum angle that may be between two face normals * at the same vertex position that their are smoothed together.<p> * * Sometimes referred to as 'crease angle'. This applies to the * GenSmoothNormals-Step. The angle is specified in degrees, so 180 is PI. * The default value is 175 degrees (all vertex normals are smoothed). The * maximum value is 175, too.<p> * * Property type: float.<p> * * Warning: setting this option may cause a severe loss of performance. The * performance is unaffected if the {@link #CONFIG_FAVOUR_SPEED} flag is * set but the output quality may be reduced. */ PP_GSN_MAX_SMOOTHING_ANGLE("PP_GSN_MAX_SMOOTHING_ANGLE"), /** * Sets the colormap (= palette) to be used to decode embedded textures in * MDL (Quake or 3DGS) files.<p> * * This must be a valid path to a file. The file is 768 (256*3) bytes * large and contains RGB triplets for each of the 256 palette entries. * The default value is colormap.lmp. If the file is not found, * a default palette (from Quake 1) is used.<p> * * Property type: string. */ IMPORT_MDL_COLORMAP("IMPORT_MDL_COLORMAP"), /** * Configures the #aiProcess_RemoveRedundantMaterials step to keep * materials matching a name in a given list.<p> * * This is a list of 1 to n strings, ' ' serves as delimiter character. * Identifiers containing whitespaces must be enclosed in *single* * quotation marks. For example:<tt> * "keep-me and_me_to anotherMaterialToBeKept \'name with whitespace\'"</tt>. * If a material matches on of these names, it will not be modified or * removed by the postprocessing step nor will other materials be replaced * by a reference to it.<p> * * This option might be useful if you are using some magic material names * to pass additional semantics through the content pipeline. This ensures * they won't be optimized away, but a general optimization is still * performed for materials not contained in the list.<p> * * Property type: String. Default value: n/a<p> * * <b>Note:</b>Linefeeds, tabs or carriage returns are treated as * whitespace. Material names are case sensitive. */ PP_RRM_EXCLUDE_LIST("PP_RRM_EXCLUDE_LIST"), /** * Configures the {@link AiPostProcessSteps#PRE_TRANSFORM_VERTICES} step * to keep the scene hierarchy. Meshes are moved to worldspace, but no * optimization is performed (read: meshes with equal materials are not * joined. The total number of meshes won't change).<p> * * This option could be of use for you if the scene hierarchy contains * important additional information which you intend to parse. * For rendering, you can still render all meshes in the scene without * any transformations.<p> * * Property type: bool. Default value: false. */ PP_PTV_KEEP_HIERARCHY("PP_PTV_KEEP_HIERARCHY"), /** * Configures the {@link AiPostProcessSteps#PRE_TRANSFORM_VERTICES} step * to normalize all vertex components into the [-1,1] range.<p> * * That is, a bounding box for the whole scene is computed, the maximum * component is taken and all meshes are scaled appropriately (uniformly * of course!). This might be useful if you don't know the spatial * dimension of the input data.<p> * * Property type: bool. Default value: false. */ PP_PTV_NORMALIZE("PP_PTV_NORMALIZE"), /** * Configures the {@link AiPostProcessSteps#FIND_DEGENERATES} step to * remove degenerated primitives from the import - immediately.<p> * * The default behaviour converts degenerated triangles to lines and * degenerated lines to points. See the documentation to the * {@link AiPostProcessSteps#FIND_DEGENERATES} step for a detailed example * of the various ways to get rid of these lines and points if you don't * want them.<p> * * Property type: bool. Default value: false. */ PP_FD_REMOVE("PP_FD_REMOVE") // // --------------------------------------------------------------------------- // /** @brief Configures the #aiProcess_OptimizeGraph step to preserve nodes // * matching a name in a given list. // * // * This is a list of 1 to n strings, ' ' serves as delimiter character. // * Identifiers containing whitespaces must be enclosed in *single* // * quotation marks. For example:<tt> // * "keep-me and_me_to anotherNodeToBeKept \'name with whitespace\'"</tt>. // * If a node matches on of these names, it will not be modified or // * removed by the postprocessing step.<br> // * This option might be useful if you are using some magic node names // * to pass additional semantics through the content pipeline. This ensures // * they won't be optimized away, but a general optimization is still // * performed for nodes not contained in the list. // * Property type: String. Default value: n/a // * @note Linefeeds, tabs or carriage returns are treated as whitespace. // * Node names are case sensitive. // */ // #define AI_CONFIG_PP_OG_EXCLUDE_LIST \ // "PP_OG_EXCLUDE_LIST" // // // --------------------------------------------------------------------------- // /** @brief Set the maximum number of triangles in a mesh. // * // * This is used by the "SplitLargeMeshes" PostProcess-Step to determine // * whether a mesh must be split or not. // * @note The default value is AI_SLM_DEFAULT_MAX_TRIANGLES // * Property type: integer. // */ // #define AI_CONFIG_PP_SLM_TRIANGLE_LIMIT \ // "PP_SLM_TRIANGLE_LIMIT" // // // default value for AI_CONFIG_PP_SLM_TRIANGLE_LIMIT // #if (!defined AI_SLM_DEFAULT_MAX_TRIANGLES) // # define AI_SLM_DEFAULT_MAX_TRIANGLES 1000000 // #endif // // // --------------------------------------------------------------------------- // /** @brief Set the maximum number of vertices in a mesh. // * // * This is used by the "SplitLargeMeshes" PostProcess-Step to determine // * whether a mesh must be split or not. // * @note The default value is AI_SLM_DEFAULT_MAX_VERTICES // * Property type: integer. // */ // #define AI_CONFIG_PP_SLM_VERTEX_LIMIT \ // "PP_SLM_VERTEX_LIMIT" // // // default value for AI_CONFIG_PP_SLM_VERTEX_LIMIT // #if (!defined AI_SLM_DEFAULT_MAX_VERTICES) // # define AI_SLM_DEFAULT_MAX_VERTICES 1000000 // #endif // // // --------------------------------------------------------------------------- // /** @brief Set the maximum number of bones affecting a single vertex // * // * This is used by the #aiProcess_LimitBoneWeights PostProcess-Step. // * @note The default value is AI_LBW_MAX_WEIGHTS // * Property type: integer.*/ // #define AI_CONFIG_PP_LBW_MAX_WEIGHTS \ // "PP_LBW_MAX_WEIGHTS" // // // default value for AI_CONFIG_PP_LBW_MAX_WEIGHTS // #if (!defined AI_LMW_MAX_WEIGHTS) // # define AI_LMW_MAX_WEIGHTS 0x4 // #endif // !! AI_LMW_MAX_WEIGHTS // // // --------------------------------------------------------------------------- // /** @brief Lower the deboning threshold in order to remove more bones. // * // * This is used by the #aiProcess_Debone PostProcess-Step. // * @note The default value is AI_DEBONE_THRESHOLD // * Property type: float.*/ // #define AI_CONFIG_PP_DB_THRESHOLD \ // "PP_DB_THRESHOLD" // // // default value for AI_CONFIG_PP_LBW_MAX_WEIGHTS // #if (!defined AI_DEBONE_THRESHOLD) // # define AI_DEBONE_THRESHOLD 1.0f // #endif // !! AI_DEBONE_THRESHOLD // // // --------------------------------------------------------------------------- // /** @brief Require all bones qualify for deboning before removing any // * // * This is used by the #aiProcess_Debone PostProcess-Step. // * @note The default value is 0 // * Property type: bool.*/ // #define AI_CONFIG_PP_DB_ALL_OR_NONE \ // "PP_DB_ALL_OR_NONE" // // /** @brief Default value for the #AI_CONFIG_PP_ICL_PTCACHE_SIZE property // */ // #ifndef PP_ICL_PTCACHE_SIZE // # define PP_ICL_PTCACHE_SIZE 12 // #endif // // // --------------------------------------------------------------------------- // /** @brief Set the size of the post-transform vertex cache to optimize the // * vertices for. This configures the #aiProcess_ImproveCacheLocality step. // * // * The size is given in vertices. Of course you can't know how the vertex // * format will exactly look like after the import returns, but you can still // * guess what your meshes will probably have. // * @note The default value is #PP_ICL_PTCACHE_SIZE. That results in slight // * performance improvements for most nVidia/AMD cards since 2002. // * Property type: integer. // */ // #define AI_CONFIG_PP_ICL_PTCACHE_SIZE "PP_ICL_PTCACHE_SIZE" // // // --------------------------------------------------------------------------- // /** @brief Enumerates components of the aiScene and aiMesh data structures // * that can be excluded from the import using the #aiPrpcess_RemoveComponent step. // * // * See the documentation to #aiProcess_RemoveComponent for more details. // */ // enum aiComponent // { // /** Normal vectors */ // #ifdef SWIG // aiComponent_NORMALS = 0x2, // #else // aiComponent_NORMALS = 0x2u, // #endif // // /** Tangents and bitangents go always together ... */ // #ifdef SWIG // aiComponent_TANGENTS_AND_BITANGENTS = 0x4, // #else // aiComponent_TANGENTS_AND_BITANGENTS = 0x4u, // #endif // // /** ALL color sets // * Use aiComponent_COLORn(N) to specify the N'th set */ // aiComponent_COLORS = 0x8, // // /** ALL texture UV sets // * aiComponent_TEXCOORDn(N) to specify the N'th set */ // aiComponent_TEXCOORDS = 0x10, // // /** Removes all bone weights from all meshes. // * The scenegraph nodes corresponding to the bones are NOT removed. // * use the #aiProcess_OptimizeGraph step to do this */ // aiComponent_BONEWEIGHTS = 0x20, // // /** Removes all node animations (aiScene::mAnimations). // * The corresponding scenegraph nodes are NOT removed. // * use the #aiProcess_OptimizeGraph step to do this */ // aiComponent_ANIMATIONS = 0x40, // // /** Removes all embedded textures (aiScene::mTextures) */ // aiComponent_TEXTURES = 0x80, // // /** Removes all light sources (aiScene::mLights). // * The corresponding scenegraph nodes are NOT removed. // * use the #aiProcess_OptimizeGraph step to do this */ // aiComponent_LIGHTS = 0x100, // // /** Removes all light sources (aiScene::mCameras). // * The corresponding scenegraph nodes are NOT removed. // * use the #aiProcess_OptimizeGraph step to do this */ // aiComponent_CAMERAS = 0x200, // // /** Removes all meshes (aiScene::mMeshes). */ // aiComponent_MESHES = 0x400, // // /** Removes all materials. One default material will // * be generated, so aiScene::mNumMaterials will be 1. */ // aiComponent_MATERIALS = 0x800, // // // /** This value is not used. It is just there to force the // * compiler to map this enum to a 32 Bit integer. */ // #ifndef SWIG // _aiComponent_Force32Bit = 0x9fffffff // #endif // }; // // // Remove a specific color channel 'n' // #define aiComponent_COLORSn(n) (1u << (n+20u)) // // // Remove a specific UV channel 'n' // #define aiComponent_TEXCOORDSn(n) (1u << (n+25u)) // // // --------------------------------------------------------------------------- // /** @brief Input parameter to the #aiProcess_RemoveComponent step: // * Specifies the parts of the data structure to be removed. // * // * See the documentation to this step for further details. The property // * is expected to be an integer, a bitwise combination of the // * #aiComponent flags defined above in this header. The default // * value is 0. Important: if no valid mesh is remaining after the // * step has been executed (e.g you thought it was funny to specify ALL // * of the flags defined above) the import FAILS. Mainly because there is // * no data to work on anymore ... // */ // #define AI_CONFIG_PP_RVC_FLAGS \ // "PP_RVC_FLAGS" // // // --------------------------------------------------------------------------- // /** @brief Input parameter to the #aiProcess_SortByPType step: // * Specifies which primitive types are removed by the step. // * // * This is a bitwise combination of the aiPrimitiveType flags. // * Specifying all of them is illegal, of course. A typical use would // * be to exclude all line and point meshes from the import. This // * is an integer property, its default value is 0. // */ // #define AI_CONFIG_PP_SBP_REMOVE \ // "PP_SBP_REMOVE" // // // --------------------------------------------------------------------------- // /** @brief Input parameter to the #aiProcess_FindInvalidData step: // * Specifies the floating-point accuracy for animation values. The step // * checks for animation tracks where all frame values are absolutely equal // * and removes them. This tweakable controls the epsilon for floating-point // * comparisons - two keys are considered equal if the invariant // * abs(n0-n1)>epsilon holds true for all vector respectively quaternion // * components. The default value is 0.f - comparisons are exact then. // */ // #define AI_CONFIG_PP_FID_ANIM_ACCURACY \ // "PP_FID_ANIM_ACCURACY" // // // // TransformUVCoords evaluates UV scalings // #define AI_UVTRAFO_SCALING 0x1 // // // TransformUVCoords evaluates UV rotations // #define AI_UVTRAFO_ROTATION 0x2 // // // TransformUVCoords evaluates UV translation // #define AI_UVTRAFO_TRANSLATION 0x4 // // // Everything baked together -> default value // #define AI_UVTRAFO_ALL (AI_UVTRAFO_SCALING | AI_UVTRAFO_ROTATION | AI_UVTRAFO_TRANSLATION) // // // --------------------------------------------------------------------------- // /** @brief Input parameter to the #aiProcess_TransformUVCoords step: // * Specifies which UV transformations are evaluated. // * // * This is a bitwise combination of the AI_UVTRAFO_XXX flags (integer // * property, of course). By default all transformations are enabled // * (AI_UVTRAFO_ALL). // */ // #define AI_CONFIG_PP_TUV_EVALUATE \ // "PP_TUV_EVALUATE" // // // --------------------------------------------------------------------------- // /** @brief A hint to assimp to favour speed against import quality. // * // * Enabling this option may result in faster loading, but it needn't. // * It represents just a hint to loaders and post-processing steps to use // * faster code paths, if possible. // * This property is expected to be an integer, != 0 stands for true. // * The default value is 0. // */ // #define AI_CONFIG_FAVOUR_SPEED \ // "FAVOUR_SPEED" // // // // ########################################################################### // // IMPORTER SETTINGS // // Various stuff to fine-tune the behaviour of specific importer plugins. // // ########################################################################### // // // // --------------------------------------------------------------------------- // /** @brief Set the vertex animation keyframe to be imported // * // * ASSIMP does not support vertex keyframes (only bone animation is supported). // * The library reads only one frame of models with vertex animations. // * By default this is the first frame. // * \note The default value is 0. This option applies to all importers. // * However, it is also possible to override the global setting // * for a specific loader. You can use the AI_CONFIG_IMPORT_XXX_KEYFRAME // * options (where XXX is a placeholder for the file format for which you // * want to override the global setting). // * Property type: integer. // */ // #define AI_CONFIG_IMPORT_GLOBAL_KEYFRAME "IMPORT_GLOBAL_KEYFRAME" // // #define AI_CONFIG_IMPORT_MD3_KEYFRAME "IMPORT_MD3_KEYFRAME" // #define AI_CONFIG_IMPORT_MD2_KEYFRAME "IMPORT_MD2_KEYFRAME" // #define AI_CONFIG_IMPORT_MDL_KEYFRAME "IMPORT_MDL_KEYFRAME" // #define AI_CONFIG_IMPORT_MDC_KEYFRAME "IMPORT_MDC_KEYFRAME" // #define AI_CONFIG_IMPORT_SMD_KEYFRAME "IMPORT_SMD_KEYFRAME" // #define AI_CONFIG_IMPORT_UNREAL_KEYFRAME "IMPORT_UNREAL_KEYFRAME" // // // // --------------------------------------------------------------------------- // /** @brief Configures the AC loader to collect all surfaces which have the // * "Backface cull" flag set in separate meshes. // * // * Property type: bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL \ // "IMPORT_AC_SEPARATE_BFCULL" // // // --------------------------------------------------------------------------- // /** @brief Configures whether the AC loader evaluates subdivision surfaces ( // * indicated by the presence of the 'subdiv' attribute in the file). By // * default, Assimp performs the subdivision using the standard // * Catmull-Clark algorithm // * // * * Property type: bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION \ // "IMPORT_AC_EVAL_SUBDIVISION" // // // --------------------------------------------------------------------------- // /** @brief Configures the UNREAL 3D loader to separate faces with different // * surface flags (e.g. two-sided vs. single-sided). // * // * * Property type: bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_UNREAL_HANDLE_FLAGS \ // "UNREAL_HANDLE_FLAGS" // // // --------------------------------------------------------------------------- // /** @brief Configures the terragen import plugin to compute uv's for // * terrains, if not given. Furthermore a default texture is assigned. // * // * UV coordinates for terrains are so simple to compute that you'll usually // * want to compute them on your own, if you need them. This option is intended // * for model viewers which want to offer an easy way to apply textures to // * terrains. // * * Property type: bool. Default value: false. // */ // #define AI_CONFIG_IMPORT_TER_MAKE_UVS \ // "IMPORT_TER_MAKE_UVS" // // // --------------------------------------------------------------------------- // /** @brief Configures the ASE loader to always reconstruct normal vectors // * basing on the smoothing groups loaded from the file. // * // * Some ASE files have carry invalid normals, other don't. // * * Property type: bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_ASE_RECONSTRUCT_NORMALS \ // "IMPORT_ASE_RECONSTRUCT_NORMALS" // // // --------------------------------------------------------------------------- // /** @brief Configures the M3D loader to detect and process multi-part // * Quake player models. // * // * These models usually consist of 3 files, lower.md3, upper.md3 and // * head.md3. If this property is set to true, Assimp will try to load and // * combine all three files if one of them is loaded. // * Property type: bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_MD3_HANDLE_MULTIPART \ // "IMPORT_MD3_HANDLE_MULTIPART" // // // --------------------------------------------------------------------------- // /** @brief Tells the MD3 loader which skin files to load. // * // * When loading MD3 files, Assimp checks whether a file // * <md3_file_name>_<skin_name>.skin is existing. These files are used by // * Quake III to be able to assign different skins (e.g. red and blue team) // * to models. 'default', 'red', 'blue' are typical skin names. // * Property type: String. Default value: "default". // */ // #define AI_CONFIG_IMPORT_MD3_SKIN_NAME \ // "IMPORT_MD3_SKIN_NAME" // // // --------------------------------------------------------------------------- // /** @brief Specify the Quake 3 shader file to be used for a particular // * MD3 file. This can also be a search path. // * // * By default Assimp's behaviour is as follows: If a MD3 file // * <tt><any_path>/models/<any_q3_subdir>/<model_name>/<file_name>.md3</tt> is // * loaded, the library tries to locate the corresponding shader file in // * <tt><any_path>/scripts/<model_name>.shader</tt>. This property overrides this // * behaviour. It can either specify a full path to the shader to be loaded // * or alternatively the path (relative or absolute) to the directory where // * the shaders for all MD3s to be loaded reside. Assimp attempts to open // * <tt><dir>/<model_name>.shader</tt> first, <tt><dir>/<file_name>.shader</tt> // * is the fallback file. Note that <dir> should have a terminal (back)slash. // * Property type: String. Default value: n/a. // */ // #define AI_CONFIG_IMPORT_MD3_SHADER_SRC \ // "IMPORT_MD3_SHADER_SRC" // // // --------------------------------------------------------------------------- // /** @brief Configures the LWO loader to load just one layer from the model. // * // * LWO files consist of layers and in some cases it could be useful to load // * only one of them. This property can be either a string - which specifies // * the name of the layer - or an integer - the index of the layer. If the // * property is not set the whole LWO model is loaded. Loading fails if the // * requested layer is not available. The layer index is zero-based and the // * layer name may not be empty.<br> // * Property type: Integer. Default value: all layers are loaded. // */ // #define AI_CONFIG_IMPORT_LWO_ONE_LAYER_ONLY \ // "IMPORT_LWO_ONE_LAYER_ONLY" // // // --------------------------------------------------------------------------- // /** @brief Configures the MD5 loader to not load the MD5ANIM file for // * a MD5MESH file automatically. // * // * The default strategy is to look for a file with the same name but the // * MD5ANIM extension in the same directory. If it is found, it is loaded // * and combined with the MD5MESH file. This configuration option can be // * used to disable this behaviour. // * // * * Property type: bool. Default value: false. // */ // #define AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD \ // "IMPORT_MD5_NO_ANIM_AUTOLOAD" // // // --------------------------------------------------------------------------- // /** @brief Defines the begin of the time range for which the LWS loader // * evaluates animations and computes aiNodeAnim's. // * // * Assimp provides full conversion of LightWave's envelope system, including // * pre and post conditions. The loader computes linearly subsampled animation // * chanels with the frame rate given in the LWS file. This property defines // * the start time. Note: animation channels are only generated if a node // * has at least one envelope with more tan one key assigned. This property. // * is given in frames, '0' is the first frame. By default, if this property // * is not set, the importer takes the animation start from the input LWS // * file ('FirstFrame' line)<br> // * Property type: Integer. Default value: taken from file. // * // * @see AI_CONFIG_IMPORT_LWS_ANIM_END - end of the imported time range // */ // #define AI_CONFIG_IMPORT_LWS_ANIM_START \ // "IMPORT_LWS_ANIM_START" // #define AI_CONFIG_IMPORT_LWS_ANIM_END \ // "IMPORT_LWS_ANIM_END" // // // --------------------------------------------------------------------------- // /** @brief Defines the output frame rate of the IRR loader. // * // * IRR animations are difficult to convert for Assimp and there will // * always be a loss of quality. This setting defines how many keys per second // * are returned by the converter.<br> // * Property type: integer. Default value: 100 // */ // #define AI_CONFIG_IMPORT_IRR_ANIM_FPS \ // "IMPORT_IRR_ANIM_FPS" // // // // --------------------------------------------------------------------------- // /** @brief Ogre Importer will try to load this Materialfile. // * // * Ogre Meshes contain only the MaterialName, not the MaterialFile. If there // * is no material file with the same name as the material, Ogre Importer will // * try to load this file and search the material in it. // * <br> // * Property type: String. Default value: guessed. // */ // #define AI_CONFIG_IMPORT_OGRE_MATERIAL_FILE "IMPORT_OGRE_MATERIAL_FILE" // // // // --------------------------------------------------------------------------- // /** @brief Ogre Importer detect the texture usage from its filename // * // * Normally, a texture is loaded as a colormap, if no target is specified in the // * materialfile. Is this switch is enabled, texture names ending with _n, _l, _s // * are used as normalmaps, lightmaps or specularmaps. // * <br> // * Property type: Bool. Default value: false. // */ // #define AI_CONFIG_IMPORT_OGRE_TEXTURETYPE_FROM_FILENAME "IMPORT_OGRE_TEXTURETYPE_FROM_FILENAME" // // // // // --------------------------------------------------------------------------- // /** @brief Specifies whether the IFC loader skips over IfcSpace elements. // * // * IfcSpace elements (and their geometric representations) are used to // * represent, well, free space in a building storey.<br> // * Property type: Bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS "IMPORT_IFC_SKIP_SPACE_REPRESENTATIONS" // // // // --------------------------------------------------------------------------- // /** @brief Specifies whether the IFC loader skips over // * shape representations of type 'Curve2D'. // * // * A lot of files contain both a faceted mesh representation and a outline // * with a presentation type of 'Curve2D'. Currently Assimp doesn't convert those, // * so turning this option off just clutters the log with errors.<br> // * Property type: Bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS "IMPORT_IFC_SKIP_CURVE_REPRESENTATIONS" // // // --------------------------------------------------------------------------- // /** @brief Specifies whether the IFC loader will use its own, custom triangulation // * algorithm to triangulate wall and floor meshes. // * // * If this property is set to false, walls will be either triangulated by // * #aiProcess_Triangulate or will be passed through as huge polygons with // * faked holes (i.e. holes that are connected with the outer boundary using // * a dummy edge). It is highly recommended to set this property to true // * if you want triangulated data because #aiProcess_Triangulate is known to // * have problems with the kind of polygons that the IFC loader spits out for // * complicated meshes. // * Property type: Bool. Default value: true. // */ // #define AI_CONFIG_IMPORT_IFC_CUSTOM_TRIANGULATION "IMPORT_IFC_CUSTOM_TRIANGULATION" // ; private AiConfigOptions(String name) { m_name = name; } private final String m_name; }
29,662
43.673193
101
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiIOStream.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; /** * Interface to allow custom resource loaders for jassimp.<p> * * The design is based on passing the file wholly in memory, * because Java inputstreams do not have to support seek. <p> * * Writing files from Java is unsupported. * * * @author Jesper Smith * */ public interface AiIOStream { /** * Read all data into buffer. <p> * * The whole stream should be read into the buffer. * No support is provided for partial reads. * * @param buffer Target buffer for the model data * * @return true if successful, false if an error occurred. */ boolean read(ByteBuffer buffer); /** * The total size of this stream. <p> * * @return total size of this stream */ int getFileSize(); }
2,642
31.62963
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiIOSystem.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; public interface AiIOSystem <T extends AiIOStream> { /** * * Open a new file with a given path. * When the access to the file is finished, call close() to release all associated resources * * @param path Path to the file * @param ioMode file I/O mode. Required are: "wb", "w", "wt", "rb", "r", "rt". * * @return AiIOStream or null if an error occurred */ public T open(String path, String ioMode); /** * Tests for the existence of a file at the given path. * * @param path path to the file * @return true if there is a file with this path, else false. */ public boolean exists(String path); /** * Returns the system specific directory separator.<p> * * @return System specific directory separator */ public char getOsSeparator(); /** * Closes the given file and releases all resources associated with it. * * @param file The file instance previously created by Open(). */ public void close(T file); }
2,878
34.9875
95
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiInputStreamIOStream.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URL; import java.nio.ByteBuffer; /** * Implementation of AiIOStream reading from a InputStream * * @author Jesper Smith * */ public class AiInputStreamIOStream implements AiIOStream { private final ByteArrayOutputStream os = new ByteArrayOutputStream(); public AiInputStreamIOStream(URI uri) throws IOException { this(uri.toURL()); } public AiInputStreamIOStream(URL url) throws IOException { this(url.openStream()); } public AiInputStreamIOStream(InputStream is) throws IOException { int read; byte[] data = new byte[1024]; while((read = is.read(data, 0, data.length)) != -1) { os.write(data, 0, read); } os.flush(); is.close(); } @Override public int getFileSize() { return os.size(); } @Override public boolean read(ByteBuffer buffer) { ByteBufferOutputStream bos = new ByteBufferOutputStream(buffer); try { os.writeTo(bos); } catch (IOException e) { e.printStackTrace(); return false; } return true; } /** * Internal helper class to copy the contents of an OutputStream * into a ByteBuffer. This avoids a copy. * */ private static class ByteBufferOutputStream extends OutputStream { private final ByteBuffer buffer; public ByteBufferOutputStream(ByteBuffer buffer) { this.buffer = buffer; } @Override public void write(int b) throws IOException { buffer.put((byte) b); } @Override public void write(byte b[], int off, int len) throws IOException { buffer.put(b, off, len); } } }
3,731
28.15625
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiLight.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Describes a light source.<p> * * Assimp supports multiple sorts of light sources, including * directional, point and spot lights. All of them are defined with just * a single structure and distinguished by their parameters. * Note - some file formats (such as 3DS, ASE) export a "target point" - * the point a spot light is looking at (it can even be animated). Assimp * writes the target point as a subnode of a spotlights's main node, * called "&lt;spotName&gt;.Target". However, this is just additional * information then, the transformation tracks of the main node make the * spot light already point in the right direction. */ public final class AiLight { /** * Constructor. * * @param name * @param type * @param position * @param direction * @param attenuationConstant * @param attenuationLinear * @param attenuationQuadratic * @param diffuse * @param specular * @param ambient * @param innerCone * @param outerCone */ AiLight(String name, int type, Object position, Object direction, float attenuationConstant, float attenuationLinear, float attenuationQuadratic, Object diffuse, Object specular, Object ambient, float innerCone, float outerCone) { m_name = name; m_type = AiLightType.fromRawValue(type); m_position = position; m_direction = direction; m_attenuationConstant = attenuationConstant; m_attenuationLinear = attenuationLinear; m_attenuationQuadratic = attenuationQuadratic; m_diffuse = diffuse; m_specular = specular; m_ambient = ambient; m_innerCone = innerCone; m_outerCone = outerCone; } /** * Returns the name of the light source.<p> * * There must be a node in the scenegraph with the same name. * This node specifies the position of the light in the scene * hierarchy and can be animated. * * @return the name */ public String getName() { return m_name; } /** * Returns The type of the light source. * * @return the type */ public AiLightType getType() { return m_type; } /** * Returns the position of the light.<p> * * The position is relative to the transformation of the scene graph node * corresponding to the light. The position is undefined for directional * lights.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiVector}. * * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the position */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getPosition(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_position; } /** * Returns the direction of the light.<p> * * The direction is relative to the transformation of the scene graph node * corresponding to the light. The direction is undefined for point lights. * The vector may be normalized, but it needn't..<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the position */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> V3 getDirection(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (V3) m_direction; } /** * Constant light attenuation factor.<p> * * The intensity of the light source at a given distance 'd' from * the light's position is * <code>Atten = 1/( att0 + att1 * d + att2 * d*d)</code> * This member corresponds to the att0 variable in the equation. * Naturally undefined for directional lights. * * @return the constant light attenuation factor */ public float getAttenuationConstant() { return m_attenuationConstant; } /** * Linear light attenuation factor.<p> * * The intensity of the light source at a given distance 'd' from * the light's position is * <code>Atten = 1/( att0 + att1 * d + att2 * d*d)</code> * This member corresponds to the att1 variable in the equation. * Naturally undefined for directional lights. * * @return the linear light attenuation factor */ public float getAttenuationLinear() { return m_attenuationLinear; } /** * Quadratic light attenuation factor.<p> * * The intensity of the light source at a given distance 'd' from * the light's position is * <code>Atten = 1/( att0 + att1 * d + att2 * d*d)</code> * This member corresponds to the att2 variable in the equation. * Naturally undefined for directional lights. * * @return the quadratic light attenuation factor */ public float getAttenuationQuadratic() { return m_attenuationQuadratic; } /** * Diffuse color of the light source.<p> * * The diffuse light color is multiplied with the diffuse * material color to obtain the final color that contributes * to the diffuse shading term.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiColor}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the diffuse color (alpha will be 1) */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getColorDiffuse( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (C) m_diffuse; } /** * Specular color of the light source.<p> * * The specular light color is multiplied with the specular * material color to obtain the final color that contributes * to the specular shading term.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiColor}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the specular color (alpha will be 1) */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getColorSpecular( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (C) m_specular; } /** * Ambient color of the light source.<p> * * The ambient light color is multiplied with the ambient * material color to obtain the final color that contributes * to the ambient shading term. Most renderers will ignore * this value it, is just a remaining of the fixed-function pipeline * that is still supported by quite many file formats.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiColor}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the ambient color (alpha will be 1) */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getColorAmbient( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (C) m_ambient; } /** * Inner angle of a spot light's light cone.<p> * * The spot light has maximum influence on objects inside this * angle. The angle is given in radians. It is 2PI for point * lights and undefined for directional lights. * * @return the inner angle */ public float getAngleInnerCone() { return m_innerCone; } /** * Outer angle of a spot light's light cone.<p> * * The spot light does not affect objects outside this angle. * The angle is given in radians. It is 2PI for point lights and * undefined for directional lights. The outer angle must be * greater than or equal to the inner angle. * It is assumed that the application uses a smooth * interpolation between the inner and the outer cone of the * spot light. * * @return the outer angle */ public float getAngleOuterCone() { return m_outerCone; } /** * Name. */ private final String m_name; /** * Type. */ private final AiLightType m_type; /** * Position. */ private final Object m_position; /** * Direction. */ private final Object m_direction; /** * Constant attenuation. */ private final float m_attenuationConstant; /** * Linear attenuation. */ private final float m_attenuationLinear; /** * Quadratic attenuation. */ private final float m_attenuationQuadratic; /** * Diffuse color. */ private final Object m_diffuse; /** * Specular color. */ private final Object m_specular; /** * Ambient color. */ private final Object m_ambient; /** * Inner cone of spotlight. */ private final float m_innerCone; /** * Outer cone of spotlight. */ private final float m_outerCone; }
11,606
28.914948
80
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiLightType.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * List of light types supported by {@link AiLight}. */ public enum AiLightType { /** * A directional light source.<p> * * A directional light has a well-defined direction but is infinitely far * away. That's quite a good approximation for sun light. */ DIRECTIONAL(0x1), /** * A point light source.<p> * * A point light has a well-defined position in space but no direction - * it emits light in all directions. A normal bulb is a point light. */ POINT(0x2), /** * A spot light source.<p> * * A spot light emits light in a specific angle. It has a position and a * direction it is pointing to. A good example for a spot light is a light * spot in sport arenas. */ SPOT(0x3), /** * The generic light level of the world, including the bounces of all other * lightsources. <p> * * Typically, there's at most one ambient light in a scene. * This light type doesn't have a valid position, direction, or * other properties, just a color. */ AMBIENT(0x4); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiLightType fromRawValue(int rawValue) { for (AiLightType type : AiLightType.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiLightType(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
3,961
30.951613
80
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiMaterial.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Data structure for a material.<p> * * Depending on the imported scene and scene format, individual properties * might be present or not. A list of all imported properties can be retrieved * via {@link #getProperties()}.<p> * * This class offers <code>getXXX()</code> for all supported properties. These * methods are fail-save, i.e., will return a default value when the * corresponding property is not set. To change the built in default values, * use the <code>setDefaultXXX()</code> methods.<p> * * If your application expects a certain set of properties to be available, * the {@link #hasProperties(Set)} method can be used to check whether all * these properties are actually set. If this check fails, you can still * use this material via the <code>getXXX()</code> methods without special * error handling code as the implementation guarantees to return default * values for missing properties. This check will not work on texture related * properties (i.e., properties starting with <code>TEX_</code>). */ public final class AiMaterial { /** * List of properties. */ private final List<Property> m_properties = new ArrayList<Property>(); /** * Number of textures for each type. */ private final Map<AiTextureType, Integer> m_numTextures = new EnumMap<AiTextureType, Integer>(AiTextureType.class); /** * Enumerates all supported material properties. */ public static enum PropertyKey { /** * Name. */ NAME("?mat.name", String.class), /** * Two-sided flag. */ TWO_SIDED("$mat.twosided", Integer.class), /** * Shading mode. */ SHADING_MODE("$mat.shadingm", AiShadingMode.class), /** * Wireframe flag. */ WIREFRAME("$mat.wireframe", Integer.class), /** * Blend mode. */ BLEND_MODE("$mat.blend", AiBlendMode.class), /** * Opacity. */ OPACITY("$mat.opacity", Float.class), /** * Bump scaling. */ BUMP_SCALING("$mat.bumpscaling", Float.class), /** * Shininess. */ SHININESS("$mat.shininess", Float.class), /** * Reflectivity. */ REFLECTIVITY("$mat.reflectivity", Float.class), /** * Shininess strength. */ SHININESS_STRENGTH("$mat.shinpercent", Float.class), /** * Refract index. */ REFRACTI("$mat.refracti", Float.class), /** * Diffuse color. */ COLOR_DIFFUSE("$clr.diffuse", Object.class), /** * Ambient color. */ COLOR_AMBIENT("$clr.ambient", Object.class), /** * Ambient color. */ COLOR_SPECULAR("$clr.specular", Object.class), /** * Emissive color. */ COLOR_EMISSIVE("$clr.emissive", Object.class), /** * Transparent color. */ COLOR_TRANSPARENT("$clr.transparent", Object.class), /** * Reflective color. */ COLOR_REFLECTIVE("$clr.reflective", Object.class), /** * Global background image. */ GLOBAL_BACKGROUND_IMAGE("?bg.global", String.class), /** * Texture file path. */ TEX_FILE("$tex.file", String.class), /** * Texture uv index. */ TEX_UV_INDEX("$tex.uvwsrc", Integer.class), /** * Texture blend factor. */ TEX_BLEND("$tex.blend", Float.class), /** * Texture operation. */ TEX_OP("$tex.op", AiTextureOp.class), /** * Texture map mode for u axis. */ TEX_MAP_MODE_U("$tex.mapmodeu", AiTextureMapMode.class), /** * Texture map mode for v axis. */ TEX_MAP_MODE_V("$tex.mapmodev", AiTextureMapMode.class), /** * Texture map mode for w axis. */ TEX_MAP_MODE_W("$tex.mapmodew", AiTextureMapMode.class); /** * Constructor. * * @param key key name as used by assimp * @param type key type, used for casts and checks */ private PropertyKey(String key, Class<?> type) { m_key = key; m_type = type; } /** * Key. */ private final String m_key; /** * Type. */ private final Class<?> m_type; } /** * A very primitive RTTI system for the contents of material properties. */ public static enum PropertyType { /** * Array of single-precision (32 Bit) floats. */ FLOAT(0x1), /** * The material property is a string. */ STRING(0x3), /** * Array of (32 Bit) integers. */ INTEGER(0x4), /** * Simple binary buffer, content undefined. Not convertible to anything. */ BUFFER(0x5); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static PropertyType fromRawValue(int rawValue) { for (PropertyType type : PropertyType.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private PropertyType(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; } /** * Data structure for a single material property.<p> * * As an user, you'll probably never need to deal with this data structure. * Just use the provided get() family of functions to query material * properties easily. */ public static final class Property { /** * Key. */ private final String m_key; /** * Semantic. */ private final int m_semantic; /** * Index. */ private final int m_index; /** * Type. */ private final PropertyType m_type; /** * Data. */ private final Object m_data; /** * Constructor. * * @param key * @param semantic * @param index * @param type * @param data */ Property(String key, int semantic, int index, int type, Object data) { m_key = key; m_semantic = semantic; m_index = index; m_type = PropertyType.fromRawValue(type); m_data = data; } /** * Constructor. * * @param key * @param semantic * @param index * @param type * @param dataLen */ Property(String key, int semantic, int index, int type, int dataLen) { m_key = key; m_semantic = semantic; m_index = index; m_type = PropertyType.fromRawValue(type); ByteBuffer b = ByteBuffer.allocateDirect(dataLen); b.order(ByteOrder.nativeOrder()); m_data = b; } /** * Returns the key of the property.<p> * * Keys are generally case insensitive. * * @return the key */ public String getKey() { return m_key; } /** * Textures: Specifies their exact usage semantic. * For non-texture properties, this member is always 0 * (or, better-said, #aiTextureType_NONE). * * @return the semantic */ public int getSemantic() { return m_semantic; } /** * Textures: Specifies the index of the texture. * For non-texture properties, this member is always 0. * * @return the index */ public int getIndex() { return m_index; } /** * Type information for the property.<p> * * Defines the data layout inside the data buffer. This is used * by the library internally to perform debug checks and to * utilize proper type conversions. * (It's probably a hacky solution, but it works.) * * @return the type */ public PropertyType getType() { return m_type; } /** * Binary buffer to hold the property's value. * The size of the buffer is always mDataLength. * * @return the data */ public Object getData() { return m_data; } } /** * Constructor. */ AiMaterial() { /* nothing to do */ } /** * Checks whether the given set of properties is available. * * @param keys the keys to check * @return true if all properties are available, false otherwise */ public boolean hasProperties(Set<PropertyKey> keys) { for (PropertyKey key : keys) { if (null == getProperty(key.m_key)) { return false; } } return true; } /** * Sets a default value.<p> * * The passed in Object must match the type of the key as returned by * the corresponding <code>getXXX()</code> method. * * @param key the key * @param defaultValue the new default, may not be null * @throws IllegalArgumentException if defaultValue is null or has a wrong * type */ public void setDefault(PropertyKey key, Object defaultValue) { if (null == defaultValue) { throw new IllegalArgumentException("defaultValue may not be null"); } if (key.m_type != defaultValue.getClass()) { throw new IllegalArgumentException( "defaultValue has wrong type, " + "expected: " + key.m_type + ", found: " + defaultValue.getClass()); } m_defaults.put(key, defaultValue); } // {{ Fail-save Getters /** * Returns the name of the material.<p> * * If missing, defaults to empty string * * @return the name */ public String getName() { return getTyped(PropertyKey.NAME, String.class); } /** * Returns the two-sided flag.<p> * * If missing, defaults to 0 * * @return the two-sided flag */ public int getTwoSided() { return getTyped(PropertyKey.TWO_SIDED, Integer.class); } /** * Returns the shading mode.<p> * * If missing, defaults to {@link AiShadingMode#FLAT} * * @return the shading mode */ public AiShadingMode getShadingMode() { Property p = getProperty(PropertyKey.SHADING_MODE.m_key); if (null == p || null == p.getData()) { return (AiShadingMode) m_defaults.get(PropertyKey.SHADING_MODE); } return AiShadingMode.fromRawValue((Integer) p.getData()); } /** * Returns the wireframe flag.<p> * * If missing, defaults to 0 * * @return the wireframe flag */ public int getWireframe() { return getTyped(PropertyKey.WIREFRAME, Integer.class); } /** * Returns the blend mode.<p> * * If missing, defaults to {@link AiBlendMode#DEFAULT} * * @return the blend mode */ public AiBlendMode getBlendMode() { Property p = getProperty(PropertyKey.BLEND_MODE.m_key); if (null == p || null == p.getData()) { return (AiBlendMode) m_defaults.get(PropertyKey.BLEND_MODE); } return AiBlendMode.fromRawValue((Integer) p.getData()); } /** * Returns the opacity.<p> * * If missing, defaults to 1.0 * * @return the opacity */ public float getOpacity() { return getTyped(PropertyKey.OPACITY, Float.class); } /** * Returns the bump scaling factor.<p> * * If missing, defaults to 1.0 * * @return the bump scaling factor */ public float getBumpScaling() { return getTyped(PropertyKey.BUMP_SCALING, Float.class); } /** * Returns the shininess.<p> * * If missing, defaults to 1.0 * * @return the shininess */ public float getShininess() { return getTyped(PropertyKey.SHININESS, Float.class); } /** * Returns the reflectivity.<p> * * If missing, defaults to 0.0 * * @return the reflectivity */ public float getReflectivity() { return getTyped(PropertyKey.REFLECTIVITY, Float.class); } /** * Returns the shininess strength.<p> * * If missing, defaults to 0.0 * * @return the shininess strength */ public float getShininessStrength() { return getTyped(PropertyKey.SHININESS_STRENGTH, Float.class); } /** * Returns the refract index.<p> * * If missing, defaults to 0.0 * * @return the refract index */ public float getRefractIndex() { return getTyped(PropertyKey.REFRACTI, Float.class); } /** * Returns the diffuse color.<p> * * If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the diffuse color */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getDiffuseColor( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { Property p = getProperty(PropertyKey.COLOR_DIFFUSE.m_key); if (null == p || null == p.getData()) { Object def = m_defaults.get(PropertyKey.COLOR_DIFFUSE); if (def == null) { return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f); } return (C) def; } return (C) p.getData(); } /** * Returns the ambient color.<p> * * If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the ambient color */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getAmbientColor( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { Property p = getProperty(PropertyKey.COLOR_AMBIENT.m_key); if (null == p || null == p.getData()) { Object def = m_defaults.get(PropertyKey.COLOR_AMBIENT); if (def == null) { return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f); } return (C) def; } return (C) p.getData(); } /** * Returns the specular color.<p> * * If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the specular color */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getSpecularColor( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { Property p = getProperty(PropertyKey.COLOR_SPECULAR.m_key); if (null == p || null == p.getData()) { Object def = m_defaults.get(PropertyKey.COLOR_SPECULAR); if (def == null) { return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f); } return (C) def; } return (C) p.getData(); } /** * Returns the emissive color.<p> * * If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the emissive color */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getEmissiveColor( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { Property p = getProperty(PropertyKey.COLOR_EMISSIVE.m_key); if (null == p || null == p.getData()) { Object def = m_defaults.get(PropertyKey.COLOR_EMISSIVE); if (def == null) { return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f); } return (C) def; } return (C) p.getData(); } /** * Returns the transparent color.<p> * * If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the transparent color */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getTransparentColor( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { Property p = getProperty(PropertyKey.COLOR_TRANSPARENT.m_key); if (null == p || null == p.getData()) { Object def = m_defaults.get(PropertyKey.COLOR_TRANSPARENT); if (def == null) { return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f); } return (C) def; } return (C) p.getData(); } /** * Returns the reflective color.<p> * * If missing, defaults to opaque white (1.0, 1.0, 1.0, 1.0)<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the reflective color */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> C getReflectiveColor( AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { Property p = getProperty(PropertyKey.COLOR_REFLECTIVE.m_key); if (null == p || null == p.getData()) { Object def = m_defaults.get(PropertyKey.COLOR_REFLECTIVE); if (def == null) { return (C) Jassimp.wrapColor4(1.0f, 1.0f, 1.0f, 1.0f); } return (C) def; } return (C) p.getData(); } /** * Returns the global background image.<p> * * If missing, defaults to empty string * * @return the global background image */ public String getGlobalBackgroundImage() { return getTyped(PropertyKey.GLOBAL_BACKGROUND_IMAGE, String.class); } /** * Returns the number of textures of the given type. * * @param type the type * @return the number of textures */ public int getNumTextures(AiTextureType type) { return m_numTextures.get(type); } /** * Returns the texture file.<p> * * If missing, defaults to empty string * * @param type the texture type * @param index the index in the texture stack * @return the file * @throws IndexOutOfBoundsException if index is invalid */ public String getTextureFile(AiTextureType type, int index) { checkTexRange(type, index); return getTyped(PropertyKey.TEX_FILE, type, index, String.class); } /** * Returns the index of the UV coordinate set used by the texture.<p> * * If missing, defaults to 0 * * @param type the texture type * @param index the index in the texture stack * @return the UV index * @throws IndexOutOfBoundsException if index is invalid */ public int getTextureUVIndex(AiTextureType type, int index) { checkTexRange(type, index); return getTyped(PropertyKey.TEX_UV_INDEX, type, index, Integer.class); } /** * Returns the blend factor of the texture.<p> * * If missing, defaults to 1.0 * * @param type the texture type * @param index the index in the texture stack * @return the blend factor */ public float getBlendFactor(AiTextureType type, int index) { checkTexRange(type, index); return getTyped(PropertyKey.TEX_BLEND, type, index, Float.class); } /** * Returns the texture operation.<p> * * If missing, defaults to {@link AiTextureOp#ADD} * * @param type the texture type * @param index the index in the texture stack * @return the texture operation */ public AiTextureOp getTextureOp(AiTextureType type, int index) { checkTexRange(type, index); Property p = getProperty(PropertyKey.TEX_OP.m_key); if (null == p || null == p.getData()) { return (AiTextureOp) m_defaults.get(PropertyKey.TEX_OP); } return AiTextureOp.fromRawValue((Integer) p.getData()); } /** * Returns the texture mapping mode for the u axis.<p> * * If missing, defaults to {@link AiTextureMapMode#CLAMP} * * @param type the texture type * @param index the index in the texture stack * @return the texture mapping mode */ public AiTextureMapMode getTextureMapModeU(AiTextureType type, int index) { checkTexRange(type, index); Property p = getProperty(PropertyKey.TEX_MAP_MODE_U.m_key); if (null == p || null == p.getData()) { return (AiTextureMapMode) m_defaults.get( PropertyKey.TEX_MAP_MODE_U); } return AiTextureMapMode.fromRawValue((Integer) p.getData()); } /** * Returns the texture mapping mode for the v axis.<p> * * If missing, defaults to {@link AiTextureMapMode#CLAMP} * * @param type the texture type * @param index the index in the texture stack * @return the texture mapping mode */ public AiTextureMapMode getTextureMapModeV(AiTextureType type, int index) { checkTexRange(type, index); Property p = getProperty(PropertyKey.TEX_MAP_MODE_V.m_key); if (null == p || null == p.getData()) { return (AiTextureMapMode) m_defaults.get( PropertyKey.TEX_MAP_MODE_V); } return AiTextureMapMode.fromRawValue((Integer) p.getData()); } /** * Returns the texture mapping mode for the w axis.<p> * * If missing, defaults to {@link AiTextureMapMode#CLAMP} * * @param type the texture type * @param index the index in the texture stack * @return the texture mapping mode */ public AiTextureMapMode getTextureMapModeW(AiTextureType type, int index) { checkTexRange(type, index); Property p = getProperty(PropertyKey.TEX_MAP_MODE_W.m_key); if (null == p || null == p.getData()) { return (AiTextureMapMode) m_defaults.get( PropertyKey.TEX_MAP_MODE_W); } return AiTextureMapMode.fromRawValue((Integer) p.getData()); } /** * Returns all information related to a single texture. * * @param type the texture type * @param index the index in the texture stack * @return the texture information */ public AiTextureInfo getTextureInfo(AiTextureType type, int index) { return new AiTextureInfo(type, index, getTextureFile(type, index), getTextureUVIndex(type, index), getBlendFactor(type, index), getTextureOp(type, index), getTextureMapModeW(type, index), getTextureMapModeW(type, index), getTextureMapModeW(type, index)); } // }} // {{ Generic Getters /** * Returns a single property based on its key. * * @param key the key * @return the property or null if the property is not set */ public Property getProperty(String key) { for (Property property : m_properties) { if (property.getKey().equals(key)) { return property; } } return null; } /** * Returns a single property based on its key. * * @param key the key * @param semantic the semantic type (texture type) * @param index the index * @return the property or null if the property is not set */ public Property getProperty(String key, int semantic, int index) { for (Property property : m_properties) { if (property.getKey().equals(key) && property.m_semantic == semantic && property.m_index == index) { return property; } } return null; } /** * Returns all properties of the material. * * @return the list of properties */ public List<Property> getProperties() { return m_properties; } // }} /** * Helper method. Returns typed property data. * * @param <T> type * @param key the key * @param clazz type * @return the data */ private <T> T getTyped(PropertyKey key, Class<T> clazz) { Property p = getProperty(key.m_key); if (null == p || null == p.getData()) { return clazz.cast(m_defaults.get(key)); } return clazz.cast(p.getData()); } /** * Helper method. Returns typed property data. * * @param <T> type * @param key the key * @param type the texture type * @param index the texture index * @param clazz type * @return the data */ private <T> T getTyped(PropertyKey key, AiTextureType type, int index, Class<T> clazz) { Property p = getProperty(key.m_key, AiTextureType.toRawValue(type), index); if (null == p || null == p.getData()) { return clazz.cast(m_defaults.get(key)); } return clazz.cast(p.getData()); } /** * Checks that index is valid an throw an exception if not. * * @param type the type * @param index the index to check */ private void checkTexRange(AiTextureType type, int index) { if (index < 0 || index > m_numTextures.get(type)) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + m_numTextures.get(type)); } } /** * Defaults for missing properties. */ private Map<PropertyKey, Object> m_defaults = new EnumMap<PropertyKey, Object>(PropertyKey.class); { setDefault(PropertyKey.NAME, ""); setDefault(PropertyKey.TWO_SIDED, 0); setDefault(PropertyKey.SHADING_MODE, AiShadingMode.FLAT); setDefault(PropertyKey.WIREFRAME, 0); setDefault(PropertyKey.BLEND_MODE, AiBlendMode.DEFAULT); setDefault(PropertyKey.OPACITY, 1.0f); setDefault(PropertyKey.BUMP_SCALING, 1.0f); setDefault(PropertyKey.SHININESS, 1.0f); setDefault(PropertyKey.REFLECTIVITY, 0.0f); setDefault(PropertyKey.SHININESS_STRENGTH, 0.0f); setDefault(PropertyKey.REFRACTI, 0.0f); /* bypass null checks for colors */ m_defaults.put(PropertyKey.COLOR_DIFFUSE, null); m_defaults.put(PropertyKey.COLOR_AMBIENT, null); m_defaults.put(PropertyKey.COLOR_SPECULAR, null); m_defaults.put(PropertyKey.COLOR_EMISSIVE, null); m_defaults.put(PropertyKey.COLOR_TRANSPARENT, null); m_defaults.put(PropertyKey.COLOR_REFLECTIVE, null); setDefault(PropertyKey.GLOBAL_BACKGROUND_IMAGE, ""); /* texture related values */ setDefault(PropertyKey.TEX_FILE, ""); setDefault(PropertyKey.TEX_UV_INDEX, 0); setDefault(PropertyKey.TEX_BLEND, 1.0f); setDefault(PropertyKey.TEX_OP, AiTextureOp.ADD); setDefault(PropertyKey.TEX_MAP_MODE_U, AiTextureMapMode.CLAMP); setDefault(PropertyKey.TEX_MAP_MODE_V, AiTextureMapMode.CLAMP); setDefault(PropertyKey.TEX_MAP_MODE_W, AiTextureMapMode.CLAMP); /* ensure we have defaults for everything */ for (PropertyKey key : PropertyKey.values()) { if (!m_defaults.containsKey(key)) { throw new IllegalStateException("missing default for: " + key); } } } /** * This method is used by JNI, do not call or modify. * * @param type the type * @param number the number */ @SuppressWarnings("unused") private void setTextureNumber(int type, int number) { m_numTextures.put(AiTextureType.fromRawValue(type), number); } }
33,863
27.22
80
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiMatrix4f.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; /** * Simple 4x4 matrix of floats. */ public final class AiMatrix4f { /** * Wraps the given array of floats as matrix. * <p> * * The array must have exactly 16 entries. The data in the array must be in * row-major order. * * @param data * the array to wrap, may not be null */ public AiMatrix4f(float[] data) { if (data == null) { throw new IllegalArgumentException("data may not be null"); } if (data.length != 16) { throw new IllegalArgumentException("array length is not 16"); } m_data = data; } /** * Gets an element of the matrix. * * @param row * the row * @param col * the column * @return the element at the given position */ public float get(int row, int col) { if (row < 0 || row > 3) { throw new IndexOutOfBoundsException("Index: " + row + ", Size: 4"); } if (col < 0 || col > 3) { throw new IndexOutOfBoundsException("Index: " + col + ", Size: 4"); } return m_data[row * 4 + col]; } /** * Stores the matrix in a new direct ByteBuffer with native byte order. * <p> * * The returned buffer can be passed to rendering APIs such as LWJGL, e.g., * as parameter for <code>GL20.glUniformMatrix4()</code>. Be sure to set * <code>transpose</code> to <code>true</code> in this case, as OpenGL * expects the matrix in column order. * * @return a new native order, direct ByteBuffer */ public FloatBuffer toByteBuffer() { ByteBuffer bbuf = ByteBuffer.allocateDirect(16 * 4); bbuf.order(ByteOrder.nativeOrder()); FloatBuffer fbuf = bbuf.asFloatBuffer(); fbuf.put(m_data); fbuf.flip(); return fbuf; } @Override public String toString() { StringBuilder buf = new StringBuilder(); for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { buf.append(m_data[row * 4 + col]).append(" "); } buf.append("\n"); } return buf.toString(); } /** * Data buffer. */ private final float[] m_data; }
4,243
30.671642
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiMesh.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Set; /** * A mesh represents a geometry or model with a single material. * <p> * * <h3>Data</h3> * Meshes usually consist of a number of vertices and a series of faces * referencing the vertices. In addition there might be a series of bones, each * of them addressing a number of vertices with a certain weight. Vertex data is * presented in channels with each channel containing a single per-vertex * information such as a set of texture coordinates or a normal vector.<p> * * Faces consist of one or more references to vertices, called vertex indices. * The {@link #getPrimitiveTypes()} method can be used to check what * face types are present in the mesh. Note that a single mesh can possess * faces of different types. The number of indices used by a specific face can * be retrieved with the {@link #getFaceNumIndices(int)} method. * * * <h3>API for vertex and face data</h3> * The jassimp interface for accessing vertex and face data is not a one-to-one * mapping of the c/c++ interface. The c/c++ interface uses an object-oriented * approach to represent data, which provides a considerable * overhead using a naive java based realization (cache locality would be * unpredictable and most likely bad, bulk data transfer would be impossible). * <p> * * The jassimp interface uses flat byte buffers to store vertex and face data. * This data can be accessed through three APIs: * <ul> * <li><b>Buffer API:</b> the <code>getXXXBuffer()</code> methods return * raw data buffers. * <li><b>Direct API:</b> the <code>getXXX()</code> methods allow reading * and writing of individual data values. * <li><b>Wrapped API:</b> the <code>getWrappedXXX()</code> methods provide * an object oriented view on the data. * </ul> * * The Buffer API is optimized for use in conjunction with rendering APIs * such as LWJGL. The returned buffers are guaranteed to have native byte order * and to be direct byte buffers. They can be passed directly to LWJGL * methods, e.g., to fill VBOs with data. Each invocation of a * <code>getXXXBuffer()</code> method will return a new view of the internal * buffer, i.e., if is safe to use the relative byte buffer operations. * The Buffer API provides the best performance of all three APIs, especially * if large data volumes have to be processed.<p> * * The Direct API provides an easy to use interface for reading and writing * individual data values. Its performance is comparable to the Buffer API's * performance for these operations. The main difference to the Buffer API is * the missing support for bulk operations. If you intend to retrieve or modify * large subsets of the raw data consider using the Buffer API, especially * if the subsets are contiguous. * <p> * * The Wrapped API offers an object oriented interface for accessing * and modifying mesh data. As the name implies, this interface is realized * through wrapper objects that provide a view on the raw data. For each * invocation of a <code>getWrappedXXX()</code> method, a new wrapper object * is created. Iterating over mesh data via this interface will create many * short-lived wrapper objects which -depending on usage and virtual machine- * may cause considerable garbage collection overhead. The Wrapped API provides * the worst performance of all three APIs, which may nevertheless still be * good enough to warrant its usage. See {@link AiWrapperProvider} for more * details on wrappers. * * * <h3>API for bones</h3> * As there is no standardized way for doing skinning in different graphics * engines, bones are not represented as flat buffers but as object structure. * Users of this library should convert this structure to the format required * by the specific graphics engine. * * * <h3>Changing Data</h3> * This class is designed to be mutable, i.e., the returned objects and buffers * may be modified. It is not possible to add/remove vertices as this would * require reallocation of the data buffers. Wrapped objects may or may not * propagate changes to the underlying data buffers. Consult the documentation * of your wrapper provider for details. The built in wrappers will propagate * changes. * <p> * Modification of face data is theoretically possible by modifying the face * buffer and the faceOffset buffer however it is strongly disadvised to do so * because it might break all algorithms that depend on the internal consistency * of these two data structures. */ public final class AiMesh { /** * Number of bytes per float value. */ private final int SIZEOF_FLOAT = Jassimp.NATIVE_FLOAT_SIZE; /** * Number of bytes per int value. */ private final int SIZEOF_INT = Jassimp.NATIVE_INT_SIZE; /** * Size of an AiVector3D in the native world. */ private final int SIZEOF_V3D = Jassimp.NATIVE_AIVEKTOR3D_SIZE; /** * The primitive types used by this mesh. */ private final Set<AiPrimitiveType> m_primitiveTypes = EnumSet.noneOf(AiPrimitiveType.class); /** * Number of vertices in this mesh. */ private int m_numVertices = 0; /** * Number of faces in this mesh. */ private int m_numFaces = 0; /** * Material used by this mesh. */ private int m_materialIndex = -1; /** * The name of the mesh. */ private String m_name = ""; /** * Buffer for vertex position data. */ private ByteBuffer m_vertices = null; /** * Buffer for faces/ indices. */ private ByteBuffer m_faces = null; /** * Index structure for m_faces.<p> * * Only used by meshes that are not pure triangular */ private ByteBuffer m_faceOffsets = null; /** * Buffer for normals. */ private ByteBuffer m_normals = null; /** * Buffer for tangents. */ private ByteBuffer m_tangents = null; /** * Buffer for bitangents. */ private ByteBuffer m_bitangents = null; /** * Vertex colors. */ private ByteBuffer[] m_colorsets = new ByteBuffer[JassimpConfig.MAX_NUMBER_COLORSETS]; /** * Number of UV components for each texture coordinate set. */ private int[] m_numUVComponents = new int[JassimpConfig.MAX_NUMBER_TEXCOORDS]; /** * Texture coordinates. */ private ByteBuffer[] m_texcoords = new ByteBuffer[JassimpConfig.MAX_NUMBER_TEXCOORDS]; /** * Bones. */ private final List<AiBone> m_bones = new ArrayList<AiBone>(); /** * This class is instantiated via JNI, no accessible constructor. */ private AiMesh() { /* nothing to do */ } /** * Returns the primitive types used by this mesh. * * @return a set of primitive types used by this mesh */ public Set<AiPrimitiveType> getPrimitiveTypes() { return m_primitiveTypes; } /** * Tells whether the mesh is a pure triangle mesh, i.e., contains only * triangular faces.<p> * * To automatically triangulate meshes the * {@link AiPostProcessSteps#TRIANGULATE} post processing option can be * used when loading the scene * * @return true if the mesh is a pure triangle mesh, false otherwise */ public boolean isPureTriangle() { return m_primitiveTypes.contains(AiPrimitiveType.TRIANGLE) && m_primitiveTypes.size() == 1; } /** * Tells whether the mesh has vertex positions.<p> * * Meshes almost always contain position data * * @return true if positions are available */ public boolean hasPositions() { return m_vertices != null; } /** * Tells whether the mesh has faces.<p> * * Meshes almost always contain faces * * @return true if faces are available */ public boolean hasFaces() { return m_faces != null; } /** * Tells whether the mesh has normals. * * @return true if normals are available */ public boolean hasNormals() { return m_normals != null; } /** * Tells whether the mesh has tangents and bitangents.<p> * * It is not possible that it contains tangents and no bitangents (or the * other way round). The existence of one of them implies that the second * is there, too. * * @return true if tangents and bitangents are available */ public boolean hasTangentsAndBitangents() { return m_tangents != null && m_tangents != null; } /** * Tells whether the mesh has a vertex color set. * * @param colorset index of the color set * @return true if colors are available */ public boolean hasColors(int colorset) { return m_colorsets[colorset] != null; } /** * Tells whether the mesh has any vertex colors.<p> * * Use {@link #hasColors(int)} to check which color sets are * available. * * @return true if any colors are available */ public boolean hasVertexColors() { for (ByteBuffer buf : m_colorsets) { if (buf != null) { return true; } } return false; } /** * Tells whether the mesh has a texture coordinate set. * * @param coords index of the texture coordinate set * @return true if texture coordinates are available */ public boolean hasTexCoords(int coords) { return m_texcoords[coords] != null; } /** * Tells whether the mesh has any texture coordinate sets.<p> * * Use {@link #hasTexCoords(int)} to check which texture coordinate * sets are available * * @return true if any texture coordinates are available */ public boolean hasTexCoords() { for (ByteBuffer buf : m_texcoords) { if (buf != null) { return true; } } return false; } /** * Tells whether the mesh has bones. * * @return true if bones are available */ public boolean hasBones() { return !m_bones.isEmpty(); } /** * Returns the bones of this mesh. * * @return a list of bones */ public List<AiBone> getBones() { return m_bones; } /** * Returns the number of vertices in this mesh. * * @return the number of vertices. */ public int getNumVertices() { return m_numVertices; } /** * Returns the number of faces in the mesh. * * @return the number of faces */ public int getNumFaces() { return m_numFaces; } /** * Returns the number of vertex indices for a single face. * * @param face the face * @return the number of indices */ public int getFaceNumIndices(int face) { if (null == m_faceOffsets) { if (face >= m_numFaces || face < 0) { throw new IndexOutOfBoundsException("Index: " + face + ", Size: " + m_numFaces); } return 3; } else { /* * no need to perform bound checks here as the array access will * throw IndexOutOfBoundsExceptions if the index is invalid */ if (face == m_numFaces - 1) { return m_faces.capacity() / 4 - m_faceOffsets.getInt(face * 4); } return m_faceOffsets.getInt((face + 1) * 4) - m_faceOffsets.getInt(face * 4); } } /** * Returns the number of UV components for a texture coordinate set.<p> * * Possible values range from 1 to 3 (1D to 3D texture coordinates) * * @param coords the coordinate set * @return the number of components */ public int getNumUVComponents(int coords) { return m_numUVComponents[coords]; } /** * Returns the material used by this mesh.<p> * * A mesh does use only a single material. If an imported model uses * multiple materials, the import splits up the mesh. Use this value * as index into the scene's material list. * * @return the material index */ public int getMaterialIndex() { return m_materialIndex; } /** * Returns the name of the mesh.<p> * * Not all meshes have a name, if no name is set an empty string is * returned. * * @return the name or an empty string if no name is set */ public String getName() { return m_name; } // CHECKSTYLE:OFF @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("Mesh(").append(m_numVertices).append(" vertices, "). append(m_numFaces).append(" faces"); if (hasNormals()) { buf.append(", normals"); } if (hasTangentsAndBitangents()) { buf.append(", (bi-)tangents"); } if (hasVertexColors()) { buf.append(", colors"); } if (hasTexCoords()) { buf.append(", texCoords"); } buf.append(")"); return buf.toString(); } // CHECKSTYLE:ON // {{ Buffer API /** * Returns a buffer containing vertex positions.<p> * * A vertex position consists of a triple of floats, the buffer will * therefore contain <code>3 * getNumVertices()</code> floats * * @return a native-order direct buffer, or null if no data is available */ public FloatBuffer getPositionBuffer() { if (m_vertices == null) { return null; } return m_vertices.asFloatBuffer(); } /** * Returns a buffer containing face data.<p> * * You should use the {@link #getIndexBuffer()} method if you are * interested in getting an index buffer used by graphics APIs such as * LWJGL.<p> * * The buffer contains all vertex indices from all faces as a flat list. If * the mesh is a pure triangle mesh, the buffer returned by this method is * identical to the buffer returned by {@link #getIndexBuffer()}. For other * meshes, the {@link #getFaceOffsets()} method can be used to retrieve * an index structure that allows addressing individual faces in the list. * * @return a native-order direct buffer, or null if no data is available */ public IntBuffer getFaceBuffer() { if (m_faces == null) { return null; } return m_faces.asIntBuffer(); } /** * Returns an index structure for the buffer returned by * {@link #getFaceBuffer()}.<p> * * You should use the {@link #getIndexBuffer()} method if you are * interested in getting an index buffer used by graphics APIs such as * LWJGL.<p> * * The returned buffer contains one integer entry for each face. This entry * specifies the offset at which the face's data is located inside the * face buffer. The difference between two subsequent entries can be used * to determine how many vertices belong to a given face (the last face * contains all entries between the offset and the end of the face buffer). * * @return a native-order direct buffer, or null if no data is available */ public IntBuffer getFaceOffsets() { if (m_faceOffsets == null) { return null; } return m_faceOffsets.asIntBuffer(); } /** * Returns a buffer containing vertex indices for the mesh's faces.<p> * * This method may only be called on pure triangle meshes, i.e., meshes * containing only triangles. The {@link #isPureTriangle()} method can be * used to check whether this is the case.<p> * * Indices are stored as integers, the buffer will therefore contain * <code>3 * getNumVertices()</code> integers (3 indices per triangle) * * @return a native-order direct buffer * @throws UnsupportedOperationException * if the mesh is not a pure triangle mesh */ public IntBuffer getIndexBuffer() { if (!isPureTriangle()) { throw new UnsupportedOperationException( "mesh is not a pure triangle mesh"); } return getFaceBuffer(); } /** * Returns a buffer containing normals.<p> * * A normal consists of a triple of floats, the buffer will * therefore contain <code>3 * getNumVertices()</code> floats * * @return a native-order direct buffer */ public FloatBuffer getNormalBuffer() { if (m_normals == null) { return null; } return m_normals.asFloatBuffer(); } /** * Returns a buffer containing tangents.<p> * * A tangent consists of a triple of floats, the buffer will * therefore contain <code>3 * getNumVertices()</code> floats * * @return a native-order direct buffer */ public FloatBuffer getTangentBuffer() { if (m_tangents == null) { return null; } return m_tangents.asFloatBuffer(); } /** * Returns a buffer containing bitangents.<p> * * A bitangent consists of a triple of floats, the buffer will * therefore contain <code>3 * getNumVertices()</code> floats * * @return a native-order direct buffer */ public FloatBuffer getBitangentBuffer() { if (m_bitangents == null) { return null; } return m_bitangents.asFloatBuffer(); } /** * Returns a buffer containing vertex colors for a color set.<p> * * A vertex color consists of 4 floats (red, green, blue and alpha), the * buffer will therefore contain <code>4 * getNumVertices()</code> floats * * @param colorset the color set * * @return a native-order direct buffer, or null if no data is available */ public FloatBuffer getColorBuffer(int colorset) { if (m_colorsets[colorset] == null) { return null; } return m_colorsets[colorset].asFloatBuffer(); } /** * Returns a buffer containing coordinates for a texture coordinate set.<p> * * A texture coordinate consists of up to 3 floats (u, v, w). The actual * number can be queried via {@link #getNumUVComponents(int)}. The * buffer will contain * <code>getNumUVComponents(coords) * getNumVertices()</code> floats * * @param coords the texture coordinate set * * @return a native-order direct buffer, or null if no data is available */ public FloatBuffer getTexCoordBuffer(int coords) { if (m_texcoords[coords] == null) { return null; } return m_texcoords[coords].asFloatBuffer(); } // }} // {{ Direct API /** * Returns the x-coordinate of a vertex position. * * @param vertex the vertex index * @return the x coordinate */ public float getPositionX(int vertex) { if (!hasPositions()) { throw new IllegalStateException("mesh has no positions"); } checkVertexIndexBounds(vertex); return m_vertices.getFloat(vertex * 3 * SIZEOF_FLOAT); } /** * Returns the y-coordinate of a vertex position. * * @param vertex the vertex index * @return the y coordinate */ public float getPositionY(int vertex) { if (!hasPositions()) { throw new IllegalStateException("mesh has no positions"); } checkVertexIndexBounds(vertex); return m_vertices.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT); } /** * Returns the z-coordinate of a vertex position. * * @param vertex the vertex index * @return the z coordinate */ public float getPositionZ(int vertex) { if (!hasPositions()) { throw new IllegalStateException("mesh has no positions"); } checkVertexIndexBounds(vertex); return m_vertices.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT); } /** * Returns a vertex reference from a face.<p> * * A face contains <code>getFaceNumIndices(face)</code> vertex references. * This method returns the n'th of these. The returned index can be passed * directly to the vertex oriented methods, such as * <code>getPosition()</code> etc. * * @param face the face * @param n the reference * @return a vertex index */ public int getFaceVertex(int face, int n) { if (!hasFaces()) { throw new IllegalStateException("mesh has no faces"); } if (face >= m_numFaces || face < 0) { throw new IndexOutOfBoundsException("Index: " + face + ", Size: " + m_numFaces); } if (n >= getFaceNumIndices(face) || n < 0) { throw new IndexOutOfBoundsException("Index: " + n + ", Size: " + getFaceNumIndices(face)); } int faceOffset = 0; if (m_faceOffsets == null) { faceOffset = 3 * face * SIZEOF_INT; } else { faceOffset = m_faceOffsets.getInt(face * SIZEOF_INT) * SIZEOF_INT; } return m_faces.getInt(faceOffset + n * SIZEOF_INT); } /** * Returns the x-coordinate of a vertex normal. * * @param vertex the vertex index * @return the x coordinate */ public float getNormalX(int vertex) { if (!hasNormals()) { throw new IllegalStateException("mesh has no normals"); } checkVertexIndexBounds(vertex); return m_normals.getFloat(vertex * 3 * SIZEOF_FLOAT); } /** * Returns the y-coordinate of a vertex normal. * * @param vertex the vertex index * @return the y coordinate */ public float getNormalY(int vertex) { if (!hasNormals()) { throw new IllegalStateException("mesh has no normals"); } checkVertexIndexBounds(vertex); return m_normals.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT); } /** * Returns the z-coordinate of a vertex normal. * * @param vertex the vertex index * @return the z coordinate */ public float getNormalZ(int vertex) { if (!hasNormals()) { throw new IllegalStateException("mesh has no normals"); } checkVertexIndexBounds(vertex); return m_normals.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT); } /** * Returns the x-coordinate of a vertex tangent. * * @param vertex the vertex index * @return the x coordinate */ public float getTangentX(int vertex) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no tangents"); } checkVertexIndexBounds(vertex); return m_tangents.getFloat(vertex * 3 * SIZEOF_FLOAT); } /** * Returns the y-coordinate of a vertex bitangent. * * @param vertex the vertex index * @return the y coordinate */ public float getTangentY(int vertex) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no bitangents"); } checkVertexIndexBounds(vertex); return m_tangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT); } /** * Returns the z-coordinate of a vertex tangent. * * @param vertex the vertex index * @return the z coordinate */ public float getTangentZ(int vertex) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no tangents"); } checkVertexIndexBounds(vertex); return m_tangents.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT); } /** * Returns the x-coordinate of a vertex tangent. * * @param vertex the vertex index * @return the x coordinate */ public float getBitangentX(int vertex) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no bitangents"); } checkVertexIndexBounds(vertex); return m_bitangents.getFloat(vertex * 3 * SIZEOF_FLOAT); } /** * Returns the y-coordinate of a vertex tangent. * * @param vertex the vertex index * @return the y coordinate */ public float getBitangentY(int vertex) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no bitangents"); } checkVertexIndexBounds(vertex); return m_bitangents.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT); } /** * Returns the z-coordinate of a vertex tangent. * * @param vertex the vertex index * @return the z coordinate */ public float getBitangentZ(int vertex) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no bitangents"); } checkVertexIndexBounds(vertex); return m_bitangents.getFloat((vertex * 3 + 2) * SIZEOF_FLOAT); } /** * Returns the red color component of a color from a vertex color set. * * @param vertex the vertex index * @param colorset the color set * @return the red color component */ public float getColorR(int vertex, int colorset) { if (!hasColors(colorset)) { throw new IllegalStateException("mesh has no colorset " + colorset); } checkVertexIndexBounds(vertex); /* bound checks for colorset are done by java for us */ return m_colorsets[colorset].getFloat(vertex * 4 * SIZEOF_FLOAT); } /** * Returns the green color component of a color from a vertex color set. * * @param vertex the vertex index * @param colorset the color set * @return the green color component */ public float getColorG(int vertex, int colorset) { if (!hasColors(colorset)) { throw new IllegalStateException("mesh has no colorset " + colorset); } checkVertexIndexBounds(vertex); /* bound checks for colorset are done by java for us */ return m_colorsets[colorset].getFloat((vertex * 4 + 1) * SIZEOF_FLOAT); } /** * Returns the blue color component of a color from a vertex color set. * * @param vertex the vertex index * @param colorset the color set * @return the blue color component */ public float getColorB(int vertex, int colorset) { if (!hasColors(colorset)) { throw new IllegalStateException("mesh has no colorset " + colorset); } checkVertexIndexBounds(vertex); /* bound checks for colorset are done by java for us */ return m_colorsets[colorset].getFloat((vertex * 4 + 2) * SIZEOF_FLOAT); } /** * Returns the alpha color component of a color from a vertex color set. * * @param vertex the vertex index * @param colorset the color set * @return the alpha color component */ public float getColorA(int vertex, int colorset) { if (!hasColors(colorset)) { throw new IllegalStateException("mesh has no colorset " + colorset); } checkVertexIndexBounds(vertex); /* bound checks for colorset are done by java for us */ return m_colorsets[colorset].getFloat((vertex * 4 + 3) * SIZEOF_FLOAT); } /** * Returns the u component of a coordinate from a texture coordinate set. * * @param vertex the vertex index * @param coords the texture coordinate set * @return the u component */ public float getTexCoordU(int vertex, int coords) { if (!hasTexCoords(coords)) { throw new IllegalStateException( "mesh has no texture coordinate set " + coords); } checkVertexIndexBounds(vertex); /* bound checks for coords are done by java for us */ return m_texcoords[coords].getFloat( vertex * m_numUVComponents[coords] * SIZEOF_FLOAT); } /** * Returns the v component of a coordinate from a texture coordinate set.<p> * * This method may only be called on 2- or 3-dimensional coordinate sets. * Call <code>getNumUVComponents(coords)</code> to determine how may * coordinate components are available. * * @param vertex the vertex index * @param coords the texture coordinate set * @return the v component */ public float getTexCoordV(int vertex, int coords) { if (!hasTexCoords(coords)) { throw new IllegalStateException( "mesh has no texture coordinate set " + coords); } checkVertexIndexBounds(vertex); /* bound checks for coords are done by java for us */ if (getNumUVComponents(coords) < 2) { throw new IllegalArgumentException("coordinate set " + coords + " does not contain 2D texture coordinates"); } return m_texcoords[coords].getFloat( (vertex * m_numUVComponents[coords] + 1) * SIZEOF_FLOAT); } /** * Returns the w component of a coordinate from a texture coordinate set.<p> * * This method may only be called on 3-dimensional coordinate sets. * Call <code>getNumUVComponents(coords)</code> to determine how may * coordinate components are available. * * @param vertex the vertex index * @param coords the texture coordinate set * @return the w component */ public float getTexCoordW(int vertex, int coords) { if (!hasTexCoords(coords)) { throw new IllegalStateException( "mesh has no texture coordinate set " + coords); } checkVertexIndexBounds(vertex); /* bound checks for coords are done by java for us */ if (getNumUVComponents(coords) < 3) { throw new IllegalArgumentException("coordinate set " + coords + " does not contain 3D texture coordinates"); } return m_texcoords[coords].getFloat( (vertex * m_numUVComponents[coords] + 1) * SIZEOF_FLOAT); } // }} // {{ Wrapped API /** * Returns the vertex position as 3-dimensional vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param vertex the vertex index * @param wrapperProvider the wrapper provider (used for type inference) * @return the position wrapped as object */ public <V3, M4, C, N, Q> V3 getWrappedPosition(int vertex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { if (!hasPositions()) { throw new IllegalStateException("mesh has no positions"); } checkVertexIndexBounds(vertex); return wrapperProvider.wrapVector3f(m_vertices, vertex * 3 * SIZEOF_FLOAT, 3); } /** * Returns the vertex normal as 3-dimensional vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param vertex the vertex index * @param wrapperProvider the wrapper provider (used for type inference) * @return the normal wrapped as object */ public <V3, M4, C, N, Q> V3 getWrappedNormal(int vertex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { if (!hasNormals()) { throw new IllegalStateException("mesh has no positions"); } checkVertexIndexBounds(vertex); return wrapperProvider.wrapVector3f(m_normals, vertex * 3 * SIZEOF_FLOAT, 3); } /** * Returns the vertex tangent as 3-dimensional vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param vertex the vertex index * @param wrapperProvider the wrapper provider (used for type inference) * @return the tangent wrapped as object */ public <V3, M4, C, N, Q> V3 getWrappedTangent(int vertex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no tangents"); } checkVertexIndexBounds(vertex); return wrapperProvider.wrapVector3f(m_tangents, vertex * 3 * SIZEOF_FLOAT, 3); } /** * Returns the vertex bitangent as 3-dimensional vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param vertex the vertex index * @param wrapperProvider the wrapper provider (used for type inference) * @return the bitangent wrapped as object */ public <V3, M4, C, N, Q> V3 getWrappedBitangent(int vertex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { if (!hasTangentsAndBitangents()) { throw new IllegalStateException("mesh has no bitangents"); } checkVertexIndexBounds(vertex); return wrapperProvider.wrapVector3f(m_bitangents, vertex * 3 * SIZEOF_FLOAT, 3); } /** * Returns the vertex color.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiColor}. * * @param vertex the vertex index * @param colorset the color set * @param wrapperProvider the wrapper provider (used for type inference) * @return the vertex color wrapped as object */ public <V3, M4, C, N, Q> C getWrappedColor(int vertex, int colorset, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { if (!hasColors(colorset)) { throw new IllegalStateException("mesh has no colorset " + colorset); } checkVertexIndexBounds(vertex); return wrapperProvider.wrapColor( m_colorsets[colorset], vertex * 4 * SIZEOF_FLOAT); } /** * Returns the texture coordinates as n-dimensional vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param vertex the vertex index * @param coords the texture coordinate set * @param wrapperProvider the wrapper provider (used for type inference) * @return the texture coordinates wrapped as object */ public <V3, M4, C, N, Q> V3 getWrappedTexCoords(int vertex, int coords, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { if (!hasTexCoords(coords)) { throw new IllegalStateException( "mesh has no texture coordinate set " + coords); } checkVertexIndexBounds(vertex); return wrapperProvider.wrapVector3f(m_texcoords[coords], vertex * 3 * SIZEOF_FLOAT, getNumUVComponents(coords)); } // }} // {{ Helpers /** * Throws an exception if the vertex index is not in the allowed range. * * @param vertex the index to check */ private void checkVertexIndexBounds(int vertex) { if (vertex >= m_numVertices || vertex < 0) { throw new IndexOutOfBoundsException("Index: " + vertex + ", Size: " + m_numVertices); } } // }} // {{ JNI interface /* * Channel constants used by allocate data channel. Do not modify or use * as these may change at will */ // CHECKSTYLE:OFF private static final int NORMALS = 0; private static final int TANGENTS = 1; private static final int BITANGENTS = 2; private static final int COLORSET = 3; private static final int TEXCOORDS_1D = 4; private static final int TEXCOORDS_2D = 5; private static final int TEXCOORDS_3D = 6; // CHECKSTYLE:ON /** * This method is used by JNI. Do not call or modify.<p> * * Sets the primitive types enum set * * @param types the bitwise or'ed c/c++ aiPrimitiveType enum values */ @SuppressWarnings("unused") private void setPrimitiveTypes(int types) { AiPrimitiveType.fromRawValue(m_primitiveTypes, types); } /** * This method is used by JNI. Do not call or modify.<p> * * Allocates byte buffers * * @param numVertices the number of vertices in the mesh * @param numFaces the number of faces in the mesh * @param optimizedFaces set true for optimized face representation * @param faceBufferSize size of face buffer for non-optimized face * representation */ @SuppressWarnings("unused") private void allocateBuffers(int numVertices, int numFaces, boolean optimizedFaces, int faceBufferSize) { /* * the allocated buffers are native order direct byte buffers, so they * can be passed directly to LWJGL or similar graphics APIs */ /* ensure face optimization is possible */ if (optimizedFaces && !isPureTriangle()) { throw new IllegalArgumentException("mesh is not purely triangular"); } m_numVertices = numVertices; m_numFaces = numFaces; /* allocate for each vertex 3 floats */ if (m_numVertices > 0) { m_vertices = ByteBuffer.allocateDirect(numVertices * 3 * SIZEOF_FLOAT); m_vertices.order(ByteOrder.nativeOrder()); } if (m_numFaces > 0) { /* for optimized faces allocate 3 integers per face */ if (optimizedFaces) { m_faces = ByteBuffer.allocateDirect(numFaces * 3 * SIZEOF_INT); m_faces.order(ByteOrder.nativeOrder()); } /* * for non-optimized faces allocate the passed in buffer size * and allocate the face index structure */ else { m_faces = ByteBuffer.allocateDirect(faceBufferSize); m_faces.order(ByteOrder.nativeOrder()); m_faceOffsets = ByteBuffer.allocateDirect(numFaces * SIZEOF_INT); m_faceOffsets.order(ByteOrder.nativeOrder()); } } } /** * This method is used by JNI. Do not call or modify.<p> * * Allocates a byte buffer for a vertex data channel * * @param channelType the channel type * @param channelIndex sub-index, used for types that can have multiple * channels, such as texture coordinates */ @SuppressWarnings("unused") private void allocateDataChannel(int channelType, int channelIndex) { switch (channelType) { case NORMALS: m_normals = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_normals.order(ByteOrder.nativeOrder()); break; case TANGENTS: m_tangents = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_tangents.order(ByteOrder.nativeOrder()); break; case BITANGENTS: m_bitangents = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_bitangents.order(ByteOrder.nativeOrder()); break; case COLORSET: m_colorsets[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 4 * SIZEOF_FLOAT); m_colorsets[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_1D: m_numUVComponents[channelIndex] = 1; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 1 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_2D: m_numUVComponents[channelIndex] = 2; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 2 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; case TEXCOORDS_3D: m_numUVComponents[channelIndex] = 3; m_texcoords[channelIndex] = ByteBuffer.allocateDirect( m_numVertices * 3 * SIZEOF_FLOAT); m_texcoords[channelIndex].order(ByteOrder.nativeOrder()); break; default: throw new IllegalArgumentException("unsupported channel type"); } } // }} }
44,794
30.501406
82
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiMeshAnim.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * This class is a stub - mesh animations are currently not supported. */ public class AiMeshAnim { }
1,954
38.1
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiMetadataEntry.java
package jassimp; /* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ public class AiMetadataEntry { public enum AiMetadataType { AI_BOOL, AI_INT32, AI_UINT64, AI_FLOAT, AI_DOUBLE, AI_AISTRING, AI_AIVECTOR3D } private AiMetadataType mType; private Object mData; public AiMetadataType getMetaDataType() { return mType; } public Object getData() { return mData; } public static boolean getAiBoolAsBoolean(AiMetadataEntry metadataEntry) { checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_BOOL); return (boolean) metadataEntry.mData; } public static int getAiInt32AsInteger(AiMetadataEntry metadataEntry) { checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_INT32); return (int) metadataEntry.mData; } public static long getAiUint64AsLong(AiMetadataEntry metadataEntry) { checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_UINT64); return (long) metadataEntry.mData; } public static float getAiFloatAsFloat(AiMetadataEntry metadataEntry) { checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_FLOAT); return (float) metadataEntry.mData; } public static double getAiDoubleAsDouble(AiMetadataEntry metadataEntry) { checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_DOUBLE); return (double) metadataEntry.mData; } public static String getAiStringAsString(AiMetadataEntry metadataEntry) { checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_AISTRING); return (String) metadataEntry.mData; } public static AiVector getAiAiVector3DAsAiVector(AiMetadataEntry metadataEntry) { checkTypeBeforeCasting(metadataEntry, AiMetadataType.AI_AIVECTOR3D); return (AiVector) metadataEntry.mData; } private static void checkTypeBeforeCasting(AiMetadataEntry entry, AiMetadataType expectedType) { if(entry.mType != expectedType) { throw new RuntimeException("Cannot cast entry of type " + entry.mType.name() + " to " + expectedType.name()); } } }
3,878
31.596639
118
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiNode.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A node in the imported hierarchy.<p> * * Each node has name, a parent node (except for the root node), * a transformation relative to its parent and possibly several child nodes. * Simple file formats don't support hierarchical structures - for these formats * the imported scene consists of only a single root node without children. */ public final class AiNode { /** * Parent node. */ private final AiNode m_parent; /** * Mesh references. */ private final int[] m_meshReferences; /** * List of children. */ private final List<AiNode> m_children = new ArrayList<AiNode>(); /** * List of metadata entries. */ private final Map<String, AiMetadataEntry> m_metaData = new HashMap<String, AiMetadataEntry>(); /** * Buffer for transformation matrix. */ private final Object m_transformationMatrix; /** * Constructor. * * @param parent the parent node, may be null * @param transform the transform matrix * @param meshReferences array of mesh references * @param name the name of the node */ AiNode(AiNode parent, Object transform, int[] meshReferences, String name) { m_parent = parent; m_transformationMatrix = transform; m_meshReferences = meshReferences; m_name = name; if (null != m_parent) { m_parent.addChild(this); } } /** * Returns the name of this node. * * @return the name */ public String getName() { return m_name; } /** * Returns the number of child nodes.<p> * * This method exists for compatibility reasons with the native assimp API. * The returned value is identical to <code>getChildren().size()</code> * * @return the number of child nodes */ public int getNumChildren() { return getChildren().size(); } /** * Returns a 4x4 matrix that specifies the transformation relative to * the parent node.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiMatrix4f}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return a matrix */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> M4 getTransform(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (M4) m_transformationMatrix; } /** * Returns the children of this node. * * @return the children, or an empty list if the node has no children */ public List<AiNode> getChildren() { return m_children; } /** * Returns the parent node. * * @return the parent, or null of the node has no parent */ public AiNode getParent() { return m_parent; } /** * Searches the node hierarchy below (and including) this node for a node * with the specified name. * * @param name the name to look for * @return the first node with the given name, or null if no such node * exists */ public AiNode findNode(String name) { /* classic recursive depth first search */ if (m_name.equals(name)) { return this; } for (AiNode child : m_children) { if (null != child.findNode(name)) { return child; } } return null; } /** * Returns the number of meshes references by this node.<p> * * This method exists for compatibility with the native assimp API. * The returned value is identical to <code>getMeshes().length</code> * * @return the number of references */ public int getNumMeshes() { return m_meshReferences.length; } /** * Returns the meshes referenced by this node.<p> * * Each entry is an index into the mesh list stored in {@link AiScene}. * * @return an array of indices */ public int[] getMeshes() { return m_meshReferences; } /** * Returns the metadata entries for this node.<p> * * Consult the original Doxygen for importer_notes to * see which formats have metadata and what to expect. * * @return A map of metadata names to entries. */ public Map<String, AiMetadataEntry> getMetadata() { return m_metaData; } /** * Adds a child node. * * @param child the child to add */ void addChild(AiNode child) { m_children.add(child); } /** * Name. */ private final String m_name; }
6,880
26.8583
100
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiNodeAnim.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * Describes the animation of a single node.<p> * * The node name ({@link #getNodeName()} specifies the bone/node which is * affected by this animation channel. The keyframes are given in three * separate series of values, one each for position, rotation and scaling. * The transformation matrix computed from these values replaces the node's * original transformation matrix at a specific time.<p> * * This means all keys are absolute and not relative to the bone default pose. * The order in which the transformations are applied is - as usual - * scaling, rotation, translation.<p> * * <b>Note:</b> All keys are returned in their correct, chronological order. * Duplicate keys don't pass the validation step. Most likely there * will be no negative time values, but they are not forbidden also (so * implementations need to cope with them!)<p> * * Like {@link AiMesh}, the animation related classes offer a Buffer API, a * Direct API and a wrapped API. Please consult the documentation of * {@link AiMesh} for a description and comparison of these APIs. */ public final class AiNodeAnim { /** * Size of one position key entry. */ private final int POS_KEY_SIZE = Jassimp.NATIVE_AIVEKTORKEY_SIZE; /** * Size of one rotation key entry. */ private final int ROT_KEY_SIZE = Jassimp.NATIVE_AIQUATKEY_SIZE; /** * Size of one scaling key entry. */ private final int SCALE_KEY_SIZE = Jassimp.NATIVE_AIVEKTORKEY_SIZE; /** * Constructor. * * @param nodeName name of corresponding scene graph node * @param numPosKeys number of position keys * @param numRotKeys number of rotation keys * @param numScaleKeys number of scaling keys * @param preBehavior behavior before animation start * @param postBehavior behavior after animation end */ AiNodeAnim(String nodeName, int numPosKeys, int numRotKeys, int numScaleKeys, int preBehavior, int postBehavior) { m_nodeName = nodeName; m_numPosKeys = numPosKeys; m_numRotKeys = numRotKeys; m_numScaleKeys = numScaleKeys; m_preState = AiAnimBehavior.fromRawValue(preBehavior); m_postState = AiAnimBehavior.fromRawValue(postBehavior); m_posKeys = ByteBuffer.allocateDirect(numPosKeys * POS_KEY_SIZE); m_posKeys.order(ByteOrder.nativeOrder()); m_rotKeys = ByteBuffer.allocateDirect(numRotKeys * ROT_KEY_SIZE); m_rotKeys.order(ByteOrder.nativeOrder()); m_scaleKeys = ByteBuffer.allocateDirect(numScaleKeys * SCALE_KEY_SIZE); m_scaleKeys.order(ByteOrder.nativeOrder()); } /** * Returns the name of the scene graph node affected by this animation.<p> * * The node must exist and it must be unique. * * @return the name of the affected node */ public String getNodeName() { return m_nodeName; } /** * Returns the number of position keys. * * @return the number of position keys */ public int getNumPosKeys() { return m_numPosKeys; } /** * Returns the buffer with position keys of this animation channel.<p> * * Position keys consist of a time value (double) and a position (3D vector * of floats), resulting in a total of 20 bytes per entry. * The buffer contains {@link #getNumPosKeys()} of these entries.<p> * * If there are position keys, there will also be at least one * scaling and one rotation key.<p> * * @return a native order, direct ByteBuffer */ public ByteBuffer getPosKeyBuffer() { ByteBuffer buf = m_posKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; } /** * Returns the time component of the specified position key. * * @param keyIndex the index of the position key * @return the time component */ public double getPosKeyTime(int keyIndex) { return m_posKeys.getDouble(POS_KEY_SIZE * keyIndex); } /** * Returns the position x component of the specified position key. * * @param keyIndex the index of the position key * @return the x component */ public float getPosKeyX(int keyIndex) { return m_posKeys.getFloat(POS_KEY_SIZE * keyIndex + 8); } /** * Returns the position y component of the specified position key. * * @param keyIndex the index of the position key * @return the y component */ public float getPosKeyY(int keyIndex) { return m_posKeys.getFloat(POS_KEY_SIZE * keyIndex + 12); } /** * Returns the position z component of the specified position key. * * @param keyIndex the index of the position key * @return the z component */ public float getPosKeyZ(int keyIndex) { return m_posKeys.getFloat(POS_KEY_SIZE * keyIndex + 16); } /** * Returns the position as vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the position as vector */ public <V3, M4, C, N, Q> V3 getPosKeyVector(int keyIndex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return wrapperProvider.wrapVector3f(m_posKeys, POS_KEY_SIZE * keyIndex + 8, 3); } /** * Returns the number of rotation keys. * * @return the number of rotation keys */ public int getNumRotKeys() { return m_numRotKeys; } /** * Returns the buffer with rotation keys of this animation channel.<p> * * Rotation keys consist of a time value (double) and a quaternion (4D * vector of floats), resulting in a total of 24 bytes per entry. The * buffer contains {@link #getNumRotKeys()} of these entries.<p> * * If there are rotation keys, there will also be at least one * scaling and one position key. * * @return a native order, direct ByteBuffer */ public ByteBuffer getRotKeyBuffer() { ByteBuffer buf = m_rotKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; } /** * Returns the time component of the specified rotation key. * * @param keyIndex the index of the position key * @return the time component */ public double getRotKeyTime(int keyIndex) { return m_rotKeys.getDouble(ROT_KEY_SIZE * keyIndex); } /** * Returns the rotation w component of the specified rotation key. * * @param keyIndex the index of the position key * @return the w component */ public float getRotKeyW(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 8); } /** * Returns the rotation x component of the specified rotation key. * * @param keyIndex the index of the position key * @return the x component */ public float getRotKeyX(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 12); } /** * Returns the rotation y component of the specified rotation key. * * @param keyIndex the index of the position key * @return the y component */ public float getRotKeyY(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 16); } /** * Returns the rotation z component of the specified rotation key. * * @param keyIndex the index of the position key * @return the z component */ public float getRotKeyZ(int keyIndex) { return m_rotKeys.getFloat(ROT_KEY_SIZE * keyIndex + 20); } /** * Returns the rotation as quaternion.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiQuaternion}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the rotation as quaternion */ public <V3, M4, C, N, Q> Q getRotKeyQuaternion(int keyIndex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return wrapperProvider.wrapQuaternion(m_rotKeys, ROT_KEY_SIZE * keyIndex + 8); } /** * Returns the number of scaling keys. * * @return the number of scaling keys */ public int getNumScaleKeys() { return m_numScaleKeys; } /** * Returns the buffer with scaling keys of this animation channel.<p> * * Scaling keys consist of a time value (double) and a 3D vector of floats, * resulting in a total of 20 bytes per entry. The buffer * contains {@link #getNumScaleKeys()} of these entries.<p> * * If there are scaling keys, there will also be at least one * position and one rotation key. * * @return a native order, direct ByteBuffer */ public ByteBuffer getScaleKeyBuffer() { ByteBuffer buf = m_scaleKeys.duplicate(); buf.order(ByteOrder.nativeOrder()); return buf; } /** * Returns the time component of the specified scaling key. * * @param keyIndex the index of the position key * @return the time component */ public double getScaleKeyTime(int keyIndex) { return m_scaleKeys.getDouble(SCALE_KEY_SIZE * keyIndex); } /** * Returns the scaling x component of the specified scaling key. * * @param keyIndex the index of the position key * @return the x component */ public float getScaleKeyX(int keyIndex) { return m_scaleKeys.getFloat(SCALE_KEY_SIZE * keyIndex + 8); } /** * Returns the scaling y component of the specified scaling key. * * @param keyIndex the index of the position key * @return the y component */ public float getScaleKeyY(int keyIndex) { return m_scaleKeys.getFloat(SCALE_KEY_SIZE * keyIndex + 12); } /** * Returns the scaling z component of the specified scaling key. * * @param keyIndex the index of the position key * @return the z component */ public float getScaleKeyZ(int keyIndex) { return m_scaleKeys.getFloat(SCALE_KEY_SIZE * keyIndex + 16); } /** * Returns the scaling factor as vector.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built in behavior is to return an {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * * @return the scaling factor as vector */ public <V3, M4, C, N, Q> V3 getScaleKeyVector(int keyIndex, AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return wrapperProvider.wrapVector3f(m_scaleKeys, SCALE_KEY_SIZE * keyIndex + 8, 3); } /** * Defines how the animation behaves before the first key is encountered. * <p> * * The default value is {@link AiAnimBehavior#DEFAULT} (the original * transformation matrix of the affected node is used). * * @return the animation behavior before the first key */ public AiAnimBehavior getPreState() { return m_preState; } /** * Defines how the animation behaves after the last key was processed.<p> * * The default value is {@link AiAnimBehavior#DEFAULT} (the original * transformation matrix of the affected node is taken). * * @return the animation behavior before after the last key */ public AiAnimBehavior getPostState() { return m_postState; } /** * Node name. */ private final String m_nodeName; /** * Number of position keys. */ private final int m_numPosKeys; /** * Buffer with position keys. */ private ByteBuffer m_posKeys; /** * Number of rotation keys. */ private final int m_numRotKeys; /** * Buffer for rotation keys. */ private ByteBuffer m_rotKeys; /** * Number of scaling keys. */ private final int m_numScaleKeys; /** * Buffer for scaling keys. */ private ByteBuffer m_scaleKeys; /** * Pre animation behavior. */ private final AiAnimBehavior m_preState; /** * Post animation behavior. */ private final AiAnimBehavior m_postState; }
14,961
28.804781
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiPostProcessSteps.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.util.Set; /** * Enumerates the post processing steps supported by assimp. */ public enum AiPostProcessSteps { /** * Calculates the tangents and bitangents for the imported meshes. * <p> * * Does nothing if a mesh does not have normals. You might want this post * processing step to be executed if you plan to use tangent space * calculations such as normal mapping applied to the meshes. There's a * config setting, <tt>#AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE</tt>, which * allows you to specify a maximum smoothing angle for the algorithm. * However, usually you'll want to leave it at the default value. */ CALC_TANGENT_SPACE(0x1), /** * Identifies and joins identical vertex data sets within all imported * meshes.<p> * * After this step is run, each mesh contains unique vertices, so a vertex * may be used by multiple faces. You usually want to use this post * processing step. If your application deals with indexed geometry, this * step is compulsory or you'll just waste rendering time. <b>If this flag * is not specified</b>, no vertices are referenced by more than one face * and <b>no index buffer is required</b> for rendering. */ JOIN_IDENTICAL_VERTICES(0x2), /** * Converts all the imported data to a left-handed coordinate space.<p> * * By default the data is returned in a right-handed coordinate space (which * OpenGL prefers). In this space, +X points to the right, +Z points towards * the viewer, and +Y points upwards. In the DirectX coordinate space +X * points to the right, +Y points upwards, and +Z points away from the * viewer.<p> * * You'll probably want to consider this flag if you use Direct3D for * rendering. The #ConvertToLeftHanded flag supersedes this * setting and bundles all conversions typically required for D3D-based * applications. */ MAKE_LEFT_HANDED(0x4), /** * Triangulates all faces of all meshes.<p> * * By default the imported mesh data might contain faces with more than 3 * indices. For rendering you'll usually want all faces to be triangles. * This post processing step splits up faces with more than 3 indices into * triangles. Line and point primitives are *not* modified! If you want * 'triangles only' with no other kinds of primitives, try the following * solution: * <ul> * <li>Specify both #Triangulate and #SortByPType * <li>Ignore all point and line meshes when you process assimp's output * </ul> */ TRIANGULATE(0x8), /** * Removes some parts of the data structure (animations, materials, light * sources, cameras, textures, vertex components).<p> * * The components to be removed are specified in a separate configuration * option, <tt>#AI_CONFIG_PP_RVC_FLAGS</tt>. This is quite useful if you * don't need all parts of the output structure. Vertex colors are rarely * used today for example... Calling this step to remove unneeded data from * the pipeline as early as possible results in increased performance and a * more optimized output data structure. This step is also useful if you * want to force Assimp to recompute normals or tangents. The corresponding * steps don't recompute them if they're already there (loaded from the * source asset). By using this step you can make sure they are NOT there. * <p> * * This flag is a poor one, mainly because its purpose is usually * misunderstood. Consider the following case: a 3D model has been exported * from a CAD app, and it has per-face vertex colors. Vertex positions can't * be shared, thus the #JoinIdenticalVertices step fails to * optimize the data because of these nasty little vertex colors. Most apps * don't even process them, so it's all for nothing. By using this step, * unneeded components are excluded as early as possible thus opening more * room for internal optimizations. */ REMOVE_COMPONENT(0x10), /** * Generates normals for all faces of all meshes.<p> * * This is ignored if normals are already there at the time this flag is * evaluated. Model importers try to load them from the source file, so * they're usually already there. Face normals are shared between all points * of a single face, so a single point can have multiple normals, which * forces the library to duplicate vertices in some cases. * #JoinIdenticalVertices is *senseless* then.<p> * * This flag may not be specified together with {@link #GEN_SMOOTH_NORMALS}. */ GEN_NORMALS(0x20), /** * Generates smooth normals for all vertices in the mesh.<p> * * This is ignored if normals are already there at the time this flag is * evaluated. Model importers try to load them from the source file, so * they're usually already there.<p> * * This flag may not be specified together with {@link #GEN_NORMALS} * There's a configuration option, * <tt>#AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE</tt> which allows you to * specify an angle maximum for the normal smoothing algorithm. Normals * exceeding this limit are not smoothed, resulting in a 'hard' seam between * two faces. Using a decent angle here (e.g. 80 degrees) results in very * good visual appearance. */ GEN_SMOOTH_NORMALS(0x40), /** * Splits large meshes into smaller sub-meshes.<p> * * This is quite useful for real-time rendering, where the number of * triangles which can be maximally processed in a single draw-call is * limited by the video driver/hardware. The maximum vertex buffer is * usually limited too. Both requirements can be met with this step: you may * specify both a triangle and vertex limit for a single mesh.<p> * * The split limits can (and should!) be set through the * <tt>#AI_CONFIG_PP_SLM_VERTEX_LIMIT</tt> and * <tt>#AI_CONFIG_PP_SLM_TRIANGLE_LIMIT</tt> settings. The default values * are <tt>#AI_SLM_DEFAULT_MAX_VERTICES</tt> and * <tt>#AI_SLM_DEFAULT_MAX_TRIANGLES</tt>.<p> * * Note that splitting is generally a time-consuming task, but only if * there's something to split. The use of this step is recommended for most * users. */ SPLIT_LARGE_MESHES(0x80), /** * Removes the node graph and pre-transforms all vertices with the local * transformation matrices of their nodes.<p> * * The output scene still contains nodes, however there is only a root node * with children, each one referencing only one mesh, and each mesh * referencing one material. For rendering, you can simply render all meshes * in order - you don't need to pay attention to local transformations and * the node hierarchy. Animations are removed during this step. This step is * intended for applications without a scenegraph. The step CAN cause some * problems: if e.g. a mesh of the asset contains normals and another, using * the same material index, does not, they will be brought together, but the * first meshes's part of the normal list is zeroed. However, these * artifacts are rare.<p> * * <b>Note:</b> The <tt>#AI_CONFIG_PP_PTV_NORMALIZE</tt> configuration * property can be set to normalize the scene's spatial dimension to the * -1...1 range. */ PRE_TRANSFORM_VERTICES(0x100), /** * Limits the number of bones simultaneously affecting a single vertex to a * maximum value.<p> * * If any vertex is affected by more than the maximum number of bones, the * least important vertex weights are removed and the remaining vertex * weights are renormalized so that the weights still sum up to 1. The * default bone weight limit is 4 (defined as <tt>#AI_LMW_MAX_WEIGHTS</tt> * in config.h), but you can use the <tt>#AI_CONFIG_PP_LBW_MAX_WEIGHTS</tt> * setting to supply your own limit to the post processing step.<p> * * If you intend to perform the skinning in hardware, this post processing * step might be of interest to you. */ LIMIT_BONE_WEIGHTS(0x200), /** * Validates the imported scene data structure. This makes sure that all * indices are valid, all animations and bones are linked correctly, all * material references are correct .. etc.<p> * * It is recommended that you capture Assimp's log output if you use this * flag, so you can easily find out what's wrong if a file fails the * validation. The validator is quite strict and will find *all* * inconsistencies in the data structure... It is recommended that plugin * developers use it to debug their loaders. There are two types of * validation failures: * <ul> * <li>Error: There's something wrong with the imported data. Further * postprocessing is not possible and the data is not usable at all. The * import fails. #Importer::GetErrorString() or #aiGetErrorString() carry * the error message around.</li> * <li>Warning: There are some minor issues (e.g. 1000000 animation * keyframes with the same time), but further postprocessing and use of the * data structure is still safe. Warning details are written to the log * file, <tt>#AI_SCENE_FLAGS_VALIDATION_WARNING</tt> is set in * #aiScene::mFlags</li> * </ul> * * This post-processing step is not time-consuming. Its use is not * compulsory, but recommended. */ VALIDATE_DATA_STRUCTURE(0x400), /** * Reorders triangles for better vertex cache locality.<p> * * The step tries to improve the ACMR (average post-transform vertex cache * miss ratio) for all meshes. The implementation runs in O(n) and is * roughly based on the 'tipsify' algorithm (see <a href=" * http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf">this * paper</a>).<p> * * If you intend to render huge models in hardware, this step might be of * interest to you. The <tt>#AI_CONFIG_PP_ICL_PTCACHE_SIZE</tt>config * setting can be used to fine-tune the cache optimization. */ IMPROVE_CACHE_LOCALITY(0x800), /** * Searches for redundant/unreferenced materials and removes them.<p> * * This is especially useful in combination with the * #PretransformVertices and #OptimizeMeshes flags. Both * join small meshes with equal characteristics, but they can't do their * work if two meshes have different materials. Because several material * settings are lost during Assimp's import filters, (and because many * exporters don't check for redundant materials), huge models often have * materials which are are defined several times with exactly the same * settings.<p> * * Several material settings not contributing to the final appearance of a * surface are ignored in all comparisons (e.g. the material name). So, if * you're passing additional information through the content pipeline * (probably using *magic* material names), don't specify this flag. * Alternatively take a look at the <tt>#AI_CONFIG_PP_RRM_EXCLUDE_LIST</tt> * setting. */ REMOVE_REDUNDANT_MATERIALS(0x1000), /** * This step tries to determine which meshes have normal vectors that are * facing inwards and inverts them.<p> * * The algorithm is simple but effective: the bounding box of all vertices + * their normals is compared against the volume of the bounding box of all * vertices without their normals. This works well for most objects, * problems might occur with planar surfaces. However, the step tries to * filter such cases. The step inverts all in-facing normals. Generally it * is recommended to enable this step, although the result is not always * correct. */ FIX_INFACING_NORMALS(0x2000), /** * This step splits meshes with more than one primitive type in homogeneous * sub-meshes.<p> * * The step is executed after the triangulation step. After the step * returns, just one bit is set in aiMesh::mPrimitiveTypes. This is * especially useful for real-time rendering where point and line primitives * are often ignored or rendered separately. You can use the * <tt>#AI_CONFIG_PP_SBP_REMOVE</tt> option to specify which primitive types * you need. This can be used to easily exclude lines and points, which are * rarely used, from the import. */ SORT_BY_PTYPE(0x8000), /** * This step searches all meshes for degenerate primitives and converts them * to proper lines or points.<p> * * A face is 'degenerate' if one or more of its points are identical. To * have the degenerate stuff not only detected and collapsed but removed, * try one of the following procedures: <br> * <b>1.</b> (if you support lines and points for rendering but don't want * the degenerates)</br> * <ul> * <li>Specify the #FindDegenerates flag.</li> * <li>Set the <tt>AI_CONFIG_PP_FD_REMOVE</tt> option to 1. This will cause * the step to remove degenerate triangles from the import as soon as * they're detected. They won't pass any further pipeline steps.</li> * </ul> * <br> * <b>2.</b>(if you don't support lines and points at all)</br> * <ul> * <li>Specify the #FindDegenerates flag. * <li>Specify the #SortByPType flag. This moves line and point * primitives to separate meshes. * <li>Set the <tt>AI_CONFIG_PP_SBP_REMOVE</tt> option to * <code>aiPrimitiveType_POINTS | aiPrimitiveType_LINES</code> * to cause SortByPType to reject point and line meshes from the * scene. * </ul> * <b>Note:</b> Degenerated polygons are not necessarily evil and that's * why they're not removed by default. There are several file formats * which don't support lines or points, and some exporters bypass the * format specification and write them as degenerate triangles instead. */ FIND_DEGENERATES(0x10000), /** * This step searches all meshes for invalid data, such as zeroed normal * vectors or invalid UV coords and removes/fixes them. This is intended to * get rid of some common exporter errors.<p> * * This is especially useful for normals. If they are invalid, and the step * recognizes this, they will be removed and can later be recomputed, i.e. * by the {@link #GEN_SMOOTH_NORMALS} flag.<p> * * The step will also remove meshes that are infinitely small and reduce * animation tracks consisting of hundreds if redundant keys to a single * key. The <tt>AI_CONFIG_PP_FID_ANIM_ACCURACY</tt> config property decides * the accuracy of the check for duplicate animation tracks. */ FIND_INVALID_DATA(0x20000), /** * This step converts non-UV mappings (such as spherical or cylindrical * mapping) to proper texture coordinate channels.<p> * * Most applications will support UV mapping only, so you will probably want * to specify this step in every case. Note that Assimp is not always able * to match the original mapping implementation of the 3D app which produced * a model perfectly. It's always better to let the modelling app compute * the UV channels - 3ds max, Maya, Blender, LightWave, and Modo do this for * example.<p> * * <b>Note:</b> If this step is not requested, you'll need to process the * <tt>MATKEY_MAPPING</tt> material property in order to display all * assets properly. */ GEN_UV_COORDS(0x40000), /** * This step applies per-texture UV transformations and bakes them into * stand-alone vtexture coordinate channels.<p> * * UV transformations are specified per-texture - see the * <tt>MATKEY_UVTRANSFORM</tt> material key for more information. This * step processes all textures with transformed input UV coordinates and * generates a new (pre-transformed) UV channel which replaces the old * channel. Most applications won't support UV transformations, so you will * probably want to specify this step.<p> * * <b>Note:</b> UV transformations are usually implemented in real-time * apps by transforming texture coordinates at vertex shader stage with a * 3x3 (homogenous) transformation matrix. */ TRANSFORM_UV_COORDS(0x80000), /** * This step searches for duplicate meshes and replaces them with references * to the first mesh.<p> * * This step takes a while, so don't use it if speed is a concern. Its main * purpose is to workaround the fact that many export file formats don't * support instanced meshes, so exporters need to duplicate meshes. This * step removes the duplicates again. Please note that Assimp does not * currently support per-node material assignment to meshes, which means * that identical meshes with different materials are currently *not* * joined, although this is planned for future versions. */ FIND_INSTANCES(0x100000), /** * A postprocessing step to reduce the number of meshes.<p> * * This will, in fact, reduce the number of draw calls.<p> * * This is a very effective optimization and is recommended to be used * together with #OptimizeGraph, if possible. The flag is fully * compatible with both {@link #SPLIT_LARGE_MESHES} and * {@link #SORT_BY_PTYPE}. */ OPTIMIZE_MESHES(0x200000), /** * A postprocessing step to optimize the scene hierarchy.<p> * * Nodes without animations, bones, lights or cameras assigned are collapsed * and joined.<p> * * Node names can be lost during this step. If you use special 'tag nodes' * to pass additional information through your content pipeline, use the * <tt>#AI_CONFIG_PP_OG_EXCLUDE_LIST</tt> setting to specify a list of node * names you want to be kept. Nodes matching one of the names in this list * won't be touched or modified.<p> * * Use this flag with caution. Most simple files will be collapsed to a * single node, so complex hierarchies are usually completely lost. This is * not useful for editor environments, but probably a very effective * optimization if you just want to get the model data, convert it to your * own format, and render it as fast as possible.<p> * * This flag is designed to be used with #OptimizeMeshes for best * results.<p> * * <b>Note:</b> 'Crappy' scenes with thousands of extremely small meshes * packed in deeply nested nodes exist for almost all file formats. * {@link #OPTIMIZE_MESHES} in combination with {@link #OPTIMIZE_GRAPH} * usually fixes them all and makes them renderable. */ OPTIMIZE_GRAPH(0x400000), /** * This step flips all UV coordinates along the y-axis and adjusts material * settings and bitangents accordingly.<p> * * <b>Output UV coordinate system:</b><br> * <code><pre> * 0y|0y ---------- 1x|0y * | | * | | * | | * 0x|1y ---------- 1x|1y * </pre></code> * <p> * * You'll probably want to consider this flag if you use Direct3D for * rendering. The {@link #MAKE_LEFT_HANDED} flag supersedes this setting * and bundles all conversions typically required for D3D-based * applications. */ FLIP_UVS(0x800000), /** * This step adjusts the output face winding order to be CW.<p> * * The default face winding order is counter clockwise (CCW). * * <b>Output face order:</b> * * <code><pre> * x2 * * x0 * x1 * </pre></code> */ FLIP_WINDING_ORDER(0x1000000), /** * This step splits meshes with many bones into sub-meshes so that each * sub-mesh has fewer or as many bones as a given limit.<p> */ SPLIT_BY_BONE_COUNT(0x2000000), /** * This step removes bones losslessly or according to some threshold.<p> * * In some cases (i.e. formats that require it) exporters are forced to * assign dummy bone weights to otherwise static meshes assigned to animated * meshes. Full, weight-based skinning is expensive while animating nodes is * extremely cheap, so this step is offered to clean up the data in that * regard.<p> * * Use <tt>#AI_CONFIG_PP_DB_THRESHOLD</tt> to control this. Use * <tt>#AI_CONFIG_PP_DB_ALL_OR_NONE</tt> if you want bones removed if and * only if all bones within the scene qualify for removal. */ DEBONE(0x4000000); /** * Utility method for converting to c/c++ based integer enums from java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param set the set to convert * @return an integer based enum value (as defined by assimp) */ static long toRawValue(Set<AiPostProcessSteps> set) { long rawValue = 0L; for (AiPostProcessSteps step : set) { rawValue |= step.m_rawValue; } return rawValue; } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiPostProcessSteps(long rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final long m_rawValue; }
23,880
40.75
80
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiPrimitiveType.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.util.Set; /** * Enumerates the types of geometric primitives supported by Assimp.<p> */ public enum AiPrimitiveType { /** * A point primitive. */ POINT(0x1), /** * A line primitive. */ LINE(0x2), /** * A triangular primitive. */ TRIANGLE(0x4), /** * A higher-level polygon with more than 3 edges.<p> * * A triangle is a polygon, but polygon in this context means * "all polygons that are not triangles". The "Triangulate"-Step is provided * for your convenience, it splits all polygons in triangles (which are much * easier to handle). */ POLYGON(0x8); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param set the target set to fill * @param rawValue an integer based enum value (as defined by assimp) */ static void fromRawValue(Set<AiPrimitiveType> set, int rawValue) { for (AiPrimitiveType type : AiPrimitiveType.values()) { if ((type.m_rawValue & rawValue) != 0) { set.add(type); } } } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiPrimitiveType(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
3,459
29.350877
80
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiProgressHandler.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; public interface AiProgressHandler { boolean update(float percentage); }
1,922
39.914894
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiQuaternion.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; /** * Wrapper for a quaternion.<p> * * The wrapper is writable, i.e., changes performed via the set-methods will * modify the underlying mesh/animation. */ public final class AiQuaternion { /** * Wrapped buffer. */ private final ByteBuffer m_buffer; /** * Offset into m_buffer. */ private final int m_offset; /** * Constructor. * * @param buffer the buffer to wrap * @param offset offset into buffer */ public AiQuaternion(ByteBuffer buffer, int offset) { if (null == buffer) { throw new IllegalArgumentException("buffer may not be null"); } m_buffer = buffer; m_offset = offset; } /** * Returns the x value. * * @return the x value */ public float getX() { return m_buffer.getFloat(m_offset + 4); } /** * Returns the y value. * * @return the y value */ public float getY() { return m_buffer.getFloat(m_offset + 8); } /** * Returns the z value. * * @return the z value */ public float getZ() { return m_buffer.getFloat(m_offset + 12); } /** * Returns the w value. * * @return the w value */ public float getW() { return m_buffer.getFloat(m_offset); } /** * Sets the x component. * * @param x the new value */ public void setX(float x) { m_buffer.putFloat(m_offset + 4, x); } /** * Sets the y component. * * @param y the new value */ public void setY(float y) { m_buffer.putFloat(m_offset + 8, y); } /** * Sets the z component. * * @param z the new value */ public void setZ(float z) { m_buffer.putFloat(m_offset + 12, z); } /** * Sets the z component. * * @param w the new value */ public void setW(float w) { m_buffer.putFloat(m_offset, w); } @Override public String toString() { return "[" + getX() + ", " + getY() + ", " + getZ() + ", " + getW() + "]"; } }
4,138
23.933735
76
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiScene.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.util.ArrayList; import java.util.List; /** * The root structure of the imported data.<p> * * Everything that was imported from the given file can be accessed from here. * <p> * Jassimp copies all data into "java memory" during import and frees * resources allocated by native code after scene loading is completed. No * special care has to be taken for freeing resources, unreferenced jassimp * objects (including the scene itself) are eligible to garbage collection like * any other java object. */ public final class AiScene { /** * Constructor. */ AiScene() { /* nothing to do */ } /** * Returns the number of meshes contained in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getMeshes().size()</code> * * @return the number of meshes */ public int getNumMeshes() { return m_meshes.size(); } /** * Returns the meshes contained in the scene.<p> * * If there are no meshes in the scene, an empty collection is returned * * @return the list of meshes */ public List<AiMesh> getMeshes() { return m_meshes; } /** * Returns the number of materials in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getMaterials().size()</code> * * @return the number of materials */ public int getNumMaterials() { return m_materials.size(); } /** * Returns the list of materials.<p> * * Use the index given in each aiMesh structure to access this * array. If the {@link AiSceneFlag#INCOMPLETE} flag is not set there will * always be at least ONE material. * * @return the list of materials */ public List<AiMaterial> getMaterials() { return m_materials; } /** * Returns the number of animations in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getAnimations().size()</code> * * @return the number of materials */ public int getNumAnimations() { return m_animations.size(); } /** * Returns the list of animations. * * @return the list of animations */ public List<AiAnimation> getAnimations() { return m_animations; } /** * Returns the number of light sources in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getLights().size()</code> * * @return the number of lights */ public int getNumLights() { return m_lights.size(); } /** * Returns the list of light sources.<p> * * Light sources are fully optional, the returned list may be empty * * @return a possibly empty list of lights */ public List<AiLight> getLights() { return m_lights; } /** * Returns the number of cameras in the scene.<p> * * This method is provided for completeness reasons. It will return the * same value as <code>getCameras().size()</code> * * @return the number of cameras */ public int getNumCameras() { return m_cameras.size(); } /** * Returns the list of cameras.<p> * * Cameras are fully optional, the returned list may be empty * * @return a possibly empty list of cameras */ public List<AiCamera> getCameras() { return m_cameras; } /** * Returns the scene graph root. * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers).<p> * * The built-in behavior is to return a {@link AiVector}. * * @param wrapperProvider the wrapper provider (used for type inference) * @return the scene graph root */ @SuppressWarnings("unchecked") public <V3, M4, C, N, Q> N getSceneRoot(AiWrapperProvider<V3, M4, C, N, Q> wrapperProvider) { return (N) m_sceneRoot; } @Override public String toString() { return "AiScene (" + m_meshes.size() + " mesh/es)"; } /** * Meshes. */ private final List<AiMesh> m_meshes = new ArrayList<AiMesh>(); /** * Materials. */ private final List<AiMaterial> m_materials = new ArrayList<AiMaterial>(); /** * Animations. */ private final List<AiAnimation> m_animations = new ArrayList<AiAnimation>(); /** * Lights. */ private final List<AiLight> m_lights = new ArrayList<AiLight>(); /** * Cameras. */ private final List<AiCamera> m_cameras = new ArrayList<AiCamera>(); /** * Scene graph root. */ private Object m_sceneRoot; }
6,906
26.40873
80
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiSceneFlag.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.util.Set; /** * Status flags for {@link AiScene}s. */ public enum AiSceneFlag { /** * Specifies that the scene data structure that was imported is not * complete.<p> * * This flag bypasses some internal validations and allows the import * of animation skeletons, material libraries or camera animation paths * using Assimp. Most applications won't support such data. */ INCOMPLETE(0x1), /** * This flag is set by the validation * ({@link AiPostProcessSteps#VALIDATE_DATA_STRUCTURE * VALIDATE_DATA_STRUCTURE}) * postprocess-step if the validation is successful.<p> * * In a validated scene you can be sure that any cross references in the * data structure (e.g. vertex indices) are valid. */ VALIDATED(0x2), /** * * This flag is set by the validation * ({@link AiPostProcessSteps#VALIDATE_DATA_STRUCTURE * VALIDATE_DATA_STRUCTURE}) * postprocess-step if the validation is successful but some issues have * been found.<p> * * This can for example mean that a texture that does not exist is * referenced by a material or that the bone weights for a vertex don't sum * to 1.0 ... . In most cases you should still be able to use the import. * This flag could be useful for applications which don't capture Assimp's * log output. */ VALIDATION_WARNING(0x4), /** * This flag is currently only set by the * {@link jassimp.AiPostProcessSteps#JOIN_IDENTICAL_VERTICES * JOIN_IDENTICAL_VERTICES}.<p> * * It indicates that the vertices of the output meshes aren't in the * internal verbose format anymore. In the verbose format all vertices are * unique, no vertex is ever referenced by more than one face. */ NON_VERBOSE_FORMAT(0x8), /** * Denotes pure height-map terrain data.<p> * * Pure terrains usually consist of quads, sometimes triangles, in a * regular grid. The x,y coordinates of all vertex positions refer to the * x,y coordinates on the terrain height map, the z-axis stores the * elevation at a specific point.<p> * * TER (Terragen) and HMP (3D Game Studio) are height map formats. * <p> * Assimp is probably not the best choice for loading *huge* terrains - * fully triangulated data takes extremely much free store and should be * avoided as long as possible (typically you'll do the triangulation when * you actually need to render it). */ TERRAIN(0x10); /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param set the target set to fill * @param rawValue an integer based enum value (as defined by assimp) */ static void fromRawValue(Set<AiSceneFlag> set, int rawValue) { for (AiSceneFlag type : AiSceneFlag.values()) { if ((type.m_rawValue & rawValue) != 0) { set.add(type); } } } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiSceneFlag(int rawValue) { m_rawValue = rawValue; } }
5,356
34.243421
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiShadingMode.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Defines all shading modes supported by the library.<p> * * The list of shading modes has been taken from Blender. * See Blender documentation for more information. The API does * not distinguish between "specular" and "diffuse" shaders (thus the * specular term for diffuse shading models like Oren-Nayar remains * undefined).<p> * Again, this value is just a hint. Assimp tries to select the shader whose * most common implementation matches the original rendering results of the * 3D modeller which wrote a particular model as closely as possible. */ public enum AiShadingMode { /** * Flat shading.<p> * * Shading is done on per-face base, diffuse only. Also known as * 'faceted shading'. */ FLAT(0x1), /** * Simple Gouraud shading. */ GOURAUD(0x2), /** * Phong-Shading. */ PHONG(0x3), /** * Phong-Blinn-Shading. */ BLINN(0x4), /** * Toon-Shading per pixel.<p> * * Also known as 'comic' shader. */ TOON(0x5), /** * OrenNayar-Shading per pixel.<p> * * Extension to standard Lambertian shading, taking the roughness of the * material into account */ OREN_NAYAR(0x6), /** * Minnaert-Shading per pixel.<p> * * Extension to standard Lambertian shading, taking the "darkness" of the * material into account */ MINNAERT(0x7), /** * CookTorrance-Shading per pixel.<p> * * Special shader for metallic surfaces. */ COOK_TORRANCE(0x8), /** * No shading at all.<p> * * Constant light influence of 1.0. */ NO_SHADING(0x9), /** * Fresnel shading. */ FRESNEL(0xa); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiShadingMode fromRawValue(int rawValue) { for (AiShadingMode type : AiShadingMode.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiShadingMode(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
4,576
26.08284
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiTextureInfo.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Data structure for texture related material properties. */ public final class AiTextureInfo { /** * Constructor. * * @param type type * @param index index * @param file file * @param uvIndex uv index * @param blend blend factor * @param texOp texture operation * @param mmU map mode for u axis * @param mmV map mode for v axis * @param mmW map mode for w axis */ AiTextureInfo(AiTextureType type, int index, String file, int uvIndex, float blend, AiTextureOp texOp, AiTextureMapMode mmU, AiTextureMapMode mmV, AiTextureMapMode mmW) { m_type = type; m_index = index; m_file = file; m_uvIndex = uvIndex; m_blend = blend; m_textureOp = texOp; m_textureMapModeU = mmU; m_textureMapModeV = mmV; m_textureMapModeW = mmW; } /** * Specifies the type of the texture (e.g. diffuse, specular, ...). * * @return the type. */ public AiTextureType getType() { return m_type; } /** * Index of the texture in the texture stack.<p> * * Each type maintains a stack of textures, i.e., there may be a diffuse.0, * a diffuse.1, etc * * @return the index */ public int getIndex() { return m_index; } /** * Returns the path to the texture file. * * @return the path */ public String getFile() { return m_file; } /** * Returns the index of the UV coordinate set. * * @return the uv index */ public int getUVIndex() { return m_uvIndex; } /** * Returns the blend factor. * * @return the blend factor */ public float getBlend() { return m_blend; } /** * Returns the texture operation used to combine this texture and the * preceding texture in the stack. * * @return the texture operation */ public AiTextureOp getTextureOp() { return m_textureOp; } /** * Returns the texture map mode for U texture axis. * * @return the texture map mode */ public AiTextureMapMode getTextureMapModeU() { return m_textureMapModeU; } /** * Returns the texture map mode for V texture axis. * * @return the texture map mode */ public AiTextureMapMode getTextureMapModeV() { return m_textureMapModeV; } /** * Returns the texture map mode for W texture axis. * * @return the texture map mode */ public AiTextureMapMode getTextureMapModeW() { return m_textureMapModeW; } /** * Type. */ private final AiTextureType m_type; /** * Index. */ private final int m_index; /** * Path. */ private final String m_file; /** * UV index. */ private final int m_uvIndex; /** * Blend factor. */ private final float m_blend; /** * Texture operation. */ private final AiTextureOp m_textureOp; /** * Map mode U axis. */ private final AiTextureMapMode m_textureMapModeU; /** * Map mode V axis. */ private final AiTextureMapMode m_textureMapModeV; /** * Map mode W axis. */ private final AiTextureMapMode m_textureMapModeW; }
5,421
23.097778
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiTextureMapMode.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Defines how UV coordinates outside the [0...1] range are handled.<p> * * Commonly referred to as 'wrapping mode'. */ public enum AiTextureMapMode { /** * A texture coordinate u|v is translated to u%1|v%1. */ WRAP(0x0), /** * Texture coordinates outside [0...1] are clamped to the nearest * valid value. */ CLAMP(0x1), /** * A texture coordinate u|v becomes u%1|v%1 if (u-(u%1))%2 is zero and * 1-(u%1)|1-(v%1) otherwise. */ MIRROR(0x2), /** * If the texture coordinates for a pixel are outside [0...1] the texture * is not applied to that pixel. */ DECAL(0x3); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiTextureMapMode fromRawValue(int rawValue) { for (AiTextureMapMode type : AiTextureMapMode.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiTextureMapMode(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
3,542
30.078947
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiTextureMapping.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Defines how the mapping coords for a texture are generated.<p> * * Real-time applications typically require full UV coordinates, so the use of * the {@link AiPostProcessSteps#GEN_UV_COORDS} step is highly recommended. * It generates proper UV channels for non-UV mapped objects, as long as an * accurate description how the mapping should look like (e.g spherical) is * given. */ public enum AiTextureMapping { /** * The mapping coordinates are taken from an UV channel. * * The #AI_MATKEY_UVWSRC key specifies from which UV channel * the texture coordinates are to be taken from (remember, * meshes can have more than one UV channel). */ // aiTextureMapping_UV = 0x0, // // /** Spherical mapping */ // aiTextureMapping_SPHERE = 0x1, // // /** Cylindrical mapping */ // aiTextureMapping_CYLINDER = 0x2, // // /** Cubic mapping */ // aiTextureMapping_BOX = 0x3, // // /** Planar mapping */ // aiTextureMapping_PLANE = 0x4, // // /** Undefined mapping. Have fun. */ // aiTextureMapping_OTHER = 0x5, }
2,993
36.898734
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiTextureOp.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Defines how the Nth texture of a specific type is combined with the result * of all previous layers.<p> * * Example (left: key, right: value): <br> * <code><pre> * DiffColor0 - gray * DiffTextureOp0 - aiTextureOpMultiply * DiffTexture0 - tex1.png * DiffTextureOp0 - aiTextureOpAdd * DiffTexture1 - tex2.png * </pre></code> * * Written as equation, the final diffuse term for a specific pixel would be: * <code><pre> * diffFinal = DiffColor0 * sampleTex(DiffTexture0,UV0) + * sampleTex(DiffTexture1,UV0) * diffContrib; * </pre></code> * where 'diffContrib' is the intensity of the incoming light for that pixel. */ public enum AiTextureOp { /** * <code>T = T1 * T2</code>. */ MULTIPLY(0x0), /** * <code>T = T1 + T2</code>. */ ADD(0x1), /** * <code>T = T1 - T2</code>. */ SUBTRACT(0x2), /** * <code>T = T1 / T2</code>. */ DIVIDE(0x3), /** * <code>T = (T1 + T2) - (T1 * T2)</code> . */ SMOOTH_ADD(0x4), /** * <code>T = T1 + (T2-0.5)</code>. */ SIGNED_ADD(0x5); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiTextureOp fromRawValue(int rawValue) { for (AiTextureOp type : AiTextureOp.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiTextureOp(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
3,994
27.949275
78
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiTextureType.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Defines the purpose of a texture.<p> * * This is a very difficult topic. Different 3D packages support different * kinds of textures. For very common texture types, such as bumpmaps, the * rendering results depend on implementation details in the rendering * pipelines of these applications. Assimp loads all texture references from * the model file and tries to determine which of the predefined texture * types below is the best choice to match the original use of the texture * as closely as possible.<p> * * In content pipelines you'll usually define how textures have to be handled, * and the artists working on models have to conform to this specification, * regardless which 3D tool they're using. */ public enum AiTextureType { /** Dummy value. * * No texture, but the value to be used as 'texture semantic' * (#aiMaterialProperty::mSemantic) for all material properties * *not* related to textures. */ NONE(0), /** LEGACY API MATERIALS * Legacy refers to materials which * Were originally implemented in the specifications around 2000. * These must never be removed, as most engines support them. */ /** The texture is combined with the result of the diffuse * lighting equation. */ DIFFUSE(1), /** The texture is combined with the result of the specular * lighting equation. */ SPECULAR(2), /** The texture is combined with the result of the ambient * lighting equation. */ AMBIENT(3), /** The texture is added to the result of the lighting * calculation. It isn't influenced by incoming light. */ EMISSIVE(4), /** The texture is a height map. * * By convention, higher gray-scale values stand for * higher elevations from the base height. */ HEIGHT(5), /** The texture is a (tangent space) normal-map. * * Again, there are several conventions for tangent-space * normal maps. Assimp does (intentionally) not * distinguish here. */ NORMALS(6), /** The texture defines the glossiness of the material. * * The glossiness is in fact the exponent of the specular * (phong) lighting equation. Usually there is a conversion * function defined to map the linear color values in the * texture to a suitable exponent. Have fun. */ SHININESS(7), /** The texture defines per-pixel opacity. * * Usually 'white' means opaque and 'black' means * 'transparency'. Or quite the opposite. Have fun. */ OPACITY(8), /** Displacement texture * * The exact purpose and format is application-dependent. * Higher color values stand for higher vertex displacements. */ DISPLACEMENT(9), /** Lightmap texture (aka Ambient Occlusion) * * Both 'Lightmaps' and dedicated 'ambient occlusion maps' are * covered by this material property. The texture contains a * scaling value for the final color value of a pixel. Its * intensity is not affected by incoming light. */ LIGHTMAP(10), /** Reflection texture * * Contains the color of a perfect mirror reflection. * Rarely used, almost never for real-time applications. */ REFLECTION(11), /** PBR Materials * PBR definitions from maya and other modelling packages now use this standard. * This was originally introduced around 2012. * Support for this is in game engines like Godot, Unreal or Unity3D. * Modelling packages which use this are very common now. */ BASE_COLOR(12), NORMAL_CAMERA(13), EMISSION_COLOR(14), METALNESS(15), DIFFUSE_ROUGHNESS(16), AMBIENT_OCCLUSION(17), /** Unknown texture * * A texture reference that does not match any of the definitions * above is considered to be 'unknown'. It is still imported, * but is excluded from any further post-processing. */ UNKNOWN(18); /** * Utility method for converting from c/c++ based integer enums to java * enums.<p> * * This method is intended to be used from JNI and my change based on * implementation needs. * * @param rawValue an integer based enum value (as defined by assimp) * @return the enum value corresponding to rawValue */ static AiTextureType fromRawValue(int rawValue) { for (AiTextureType type : AiTextureType.values()) { if (type.m_rawValue == rawValue) { return type; } } throw new IllegalArgumentException("unexptected raw value: " + rawValue); } /** * Utility method for converting from java enums to c/c++ based integer * enums.<p> * * @param type the type to convert, may not be null * @return the rawValue corresponding to type */ static int toRawValue(AiTextureType type) { return type.m_rawValue; } /** * Constructor. * * @param rawValue maps java enum to c/c++ integer enum values */ private AiTextureType(int rawValue) { m_rawValue = rawValue; } /** * The mapped c/c++ integer enum value. */ private final int m_rawValue; }
7,119
31.511416
84
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiVector.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; /** * Wrapper for 3-dimensional vectors.<p> * * This wrapper is also used to represent 1- and 2-dimensional vectors. In * these cases only the x (or the x and y coordinate) will be used. * Accessing unused components will throw UnsupportedOperationExceptions.<p> * * The wrapper is writable, i.e., changes performed via the set-methods will * modify the underlying mesh. */ public final class AiVector { /** * Constructor. * * @param buffer the buffer to wrap * @param offset offset into buffer * @param numComponents number vector of components */ public AiVector(ByteBuffer buffer, int offset, int numComponents) { if (null == buffer) { throw new IllegalArgumentException("buffer may not be null"); } m_buffer = buffer; m_offset = offset; m_numComponents = numComponents; } /** * Returns the x value. * * @return the x value */ public float getX() { return m_buffer.getFloat(m_offset); } /** * Returns the y value.<p> * * May only be called on 2- or 3-dimensional vectors. * * @return the y value */ public float getY() { if (m_numComponents <= 1) { throw new UnsupportedOperationException( "vector has only 1 component"); } return m_buffer.getFloat(m_offset + 4); } /** * Returns the z value.<p> * * May only be called on 3-dimensional vectors. * * @return the z value */ public float getZ() { if (m_numComponents <= 2) { throw new UnsupportedOperationException( "vector has only 2 components"); } return m_buffer.getFloat(m_offset + 8); } /** * Sets the x component. * * @param x the new value */ public void setX(float x) { m_buffer.putFloat(m_offset, x); } /** * Sets the y component.<p> * * May only be called on 2- or 3-dimensional vectors. * * @param y the new value */ public void setY(float y) { if (m_numComponents <= 1) { throw new UnsupportedOperationException( "vector has only 1 component"); } m_buffer.putFloat(m_offset + 4, y); } /** * Sets the z component.<p> * * May only be called on 3-dimensional vectors. * * @param z the new value */ public void setZ(float z) { if (m_numComponents <= 2) { throw new UnsupportedOperationException( "vector has only 2 components"); } m_buffer.putFloat(m_offset + 8, z); } /** * Returns the number of components in this vector. * * @return the number of components */ public int getNumComponents() { return m_numComponents; } @Override public String toString() { return "[" + getX() + ", " + getY() + ", " + getZ() + "]"; } /** * Wrapped buffer. */ private final ByteBuffer m_buffer; /** * Offset into m_buffer. */ private final int m_offset; /** * Number of components. */ private final int m_numComponents; }
5,301
26.05102
76
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/AiWrapperProvider.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; /** * Provides wrapper objects for raw data buffers.<p> * * It is likely that applications using Jassimp will already have a scene * graph implementation and/ or the typical math related classes such as * vectors, matrices, etc.<p> * * To ease the integration with existing code, Jassimp can be customized to * represent the scene graph and compound data structures such as vectors and * matrices with user supplied classes.<p> * * All methods returning wrapped objects rely on the AiWrapperProvider to * create individual instances. Custom wrappers can be created by implementing * AiWrapperProvider and registering the implementation via * {@link Jassimp#setWrapperProvider(AiWrapperProvider)} <b>before</b> the * scene is imported.<p> * * The methods returning wrapped types take an AiWrapperProvider instance. This * instance must match the instance set via * {@link Jassimp#setWrapperProvider(AiWrapperProvider)}. The method parameter * is used to infer the type of the returned object. The passed in wrapper * provider is not necessarily used to actually create the wrapped object, as * the object may be cached for performance reasons. <b>It is not possible to * use different AiWrapperProviders throughout the lifetime of an imported * scene.</b> * * @param <V3> the type used to represent vectors * @param <M4> the type used to represent matrices * @param <C> the type used to represent colors * @param <N> the type used to represent scene graph nodes * @param <Q> the type used to represent quaternions */ public interface AiWrapperProvider<V3, M4, C, N, Q> { /** * Wraps a vector.<p> * * Most vectors are 3-dimensional, i.e., with 3 components. The exception * are texture coordinates, which may be 1- or 2-dimensional. A vector * consists of numComponents floats (x,y,z) starting from offset * * @param buffer the buffer to wrap * @param offset the offset into buffer * @param numComponents the number of components * @return the wrapped vector */ V3 wrapVector3f(ByteBuffer buffer, int offset, int numComponents); /** * Wraps a 4x4 matrix of floats.<p> * * The calling code will allocate a new array for each invocation of this * method. It is safe to store a reference to the passed in array and * use the array to store the matrix data. * * @param data the matrix data in row-major order * @return the wrapped matrix */ M4 wrapMatrix4f(float[] data); /** * Wraps a RGBA color.<p> * * A color consists of 4 float values (r,g,b,a) starting from offset * * @param buffer the buffer to wrap * @param offset the offset into buffer * @return the wrapped color */ C wrapColor(ByteBuffer buffer, int offset); /** * Wraps a scene graph node.<p> * * See {@link AiNode} for a description of the scene graph structure used * by assimp.<p> * * The parent node is either null or an instance returned by this method. * It is therefore safe to cast the passed in parent object to the * implementation specific type * * @param parent the parent node * @param matrix the transformation matrix * @param meshReferences array of mesh references (indexes) * @param name the name of the node * @return the wrapped scene graph node */ N wrapSceneNode(Object parent, Object matrix, int[] meshReferences, String name); /** * Wraps a quaternion.<p> * * A quaternion consists of 4 float values (w,x,y,z) starting from offset * * @param buffer the buffer to wrap * @param offset the offset into buffer * @return the wrapped quaternion */ Q wrapQuaternion(ByteBuffer buffer, int offset); }
5,756
37.38
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/JaiDebug.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.nio.ByteBuffer; /** * Debug/utility methods. */ public final class JaiDebug { /** * Pure static class, no accessible constructor. */ private JaiDebug() { /* nothing to do */ } /** * Dumps vertex positions of a mesh to stdout.<p> * * @param mesh the mesh */ public static void dumpPositions(AiMesh mesh) { if (!mesh.hasPositions()) { System.out.println("mesh has no vertex positions"); return; } for (int i = 0; i < mesh.getNumVertices(); i++) { System.out.println("[" + mesh.getPositionX(i) + ", " + mesh.getPositionY(i) + ", " + mesh.getPositionZ(i) + "]" ); } } /** * Dumps faces of a mesh to stdout.<p> * * @param mesh the mesh */ public static void dumpFaces(AiMesh mesh) { if (!mesh.hasFaces()) { System.out.println("mesh has no faces"); return; } for (int face = 0; face < mesh.getNumFaces(); face++) { int faceNumIndices = mesh.getFaceNumIndices(face); System.out.print(faceNumIndices + ": "); for (int vertex = 0; vertex < faceNumIndices; vertex++) { int reference = mesh.getFaceVertex(face, vertex); System.out.print("[" + mesh.getPositionX(reference) + ", " + mesh.getPositionY(reference) + ", " + mesh.getPositionZ(reference) + "] " ); } System.out.println(); } } /** * Dumps a vertex color set of a mesh to stdout.<p> * * @param mesh the mesh * @param colorset the color set */ public static void dumpColorset(AiMesh mesh, int colorset) { if (!mesh.hasColors(colorset)) { System.out.println("mesh has no vertex color set " + colorset); return; } for (int i = 0; i < mesh.getNumVertices(); i++) { System.out.println("[" + mesh.getColorR(i, colorset) + ", " + mesh.getColorG(i, colorset) + ", " + mesh.getColorB(i, colorset) + ", " + mesh.getColorA(i, colorset) + "]" ); } } /** * Dumps a texture coordinate set of a mesh to stdout. * * @param mesh the mesh * @param coords the coordinates */ public static void dumpTexCoords(AiMesh mesh, int coords) { if (!mesh.hasTexCoords(coords)) { System.out.println("mesh has no texture coordinate set " + coords); return; } for (int i = 0; i < mesh.getNumVertices(); i++) { int numComponents = mesh.getNumUVComponents(coords); System.out.print("[" + mesh.getTexCoordU(i, coords)); if (numComponents > 1) { System.out.print(", " + mesh.getTexCoordV(i, coords)); } if (numComponents > 2) { System.out.print(", " + mesh.getTexCoordW(i, coords)); } System.out.println("]"); } } /** * Dumps a single material property to stdout. * * @param property the property */ public static void dumpMaterialProperty(AiMaterial.Property property) { System.out.print(property.getKey() + " " + property.getSemantic() + " " + property.getIndex() + ": "); Object data = property.getData(); if (data instanceof ByteBuffer) { ByteBuffer buf = (ByteBuffer) data; for (int i = 0; i < buf.capacity(); i++) { System.out.print(Integer.toHexString(buf.get(i) & 0xFF) + " "); } System.out.println(); } else { System.out.println(data.toString()); } } /** * Dumps all properties of a material to stdout. * * @param material the material */ public static void dumpMaterial(AiMaterial material) { for (AiMaterial.Property prop : material.getProperties()) { dumpMaterialProperty(prop); } } /** * Dumps an animation channel to stdout. * * @param nodeAnim the channel */ public static void dumpNodeAnim(AiNodeAnim nodeAnim) { for (int i = 0; i < nodeAnim.getNumPosKeys(); i++) { System.out.println(i + ": " + nodeAnim.getPosKeyTime(i) + " ticks, " + nodeAnim.getPosKeyVector(i, Jassimp.BUILTIN)); } } }
6,720
31.004762
79
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/Jassimp.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; import java.io.IOException; import java.nio.ByteBuffer; import java.util.EnumSet; import java.util.Set; /** * Entry point to the jassimp library.<p> * * Use {@link #importFile(String, Set)} to load a file. * * <h3>General Notes and Pitfalls</h3> * Due to the loading via JNI, strings (for example as returned by the * <code>getName()</code> methods) are not interned. You should therefore * compare strings the way it should be done, i.e, via <code>equals()</code>. * Pointer comparison will fail. */ public final class Jassimp { /** * The native interface. * * @param filename the file to load * @param postProcessing post processing flags * @return the loaded scene, or null if an error occurred * @throws IOException if an error occurs */ private static native AiScene aiImportFile(String filename, long postProcessing, AiIOSystem<?> ioSystem, AiProgressHandler progressHandler) throws IOException; /** * The active wrapper provider. */ private static AiWrapperProvider<?, ?, ?, ?, ?> s_wrapperProvider = new AiBuiltInWrapperProvider(); /** * The library loader to load the native library. */ private static JassimpLibraryLoader s_libraryLoader = new JassimpLibraryLoader(); /** * Status flag if the library is loaded. * * Volatile to avoid problems with double checked locking. * */ private static volatile boolean s_libraryLoaded = false; /** * Lock for library loading. */ private static final Object s_libraryLoadingLock = new Object(); /** * The default wrapper provider using built in types. */ public static final AiWrapperProvider<?, ?, ?, ?, ?> BUILTIN = new AiBuiltInWrapperProvider(); /** * Imports a file via assimp without post processing. * * @param filename the file to import * @return the loaded scene * @throws IOException if an error occurs */ public static AiScene importFile(String filename) throws IOException { return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class)); } /** * Imports a file via assimp without post processing. * * @param filename the file to import * @param ioSystem ioSystem to load files, or null for default * @return the loaded scene * @throws IOException if an error occurs */ public static AiScene importFile(String filename, AiIOSystem<?> ioSystem) throws IOException { return importFile(filename, EnumSet.noneOf(AiPostProcessSteps.class), ioSystem); } /** * Imports a file via assimp. * * @param filename the file to import * @param postProcessing post processing flags * @return the loaded scene, or null if an error occurred * @throws IOException if an error occurs */ public static AiScene importFile(String filename, Set<AiPostProcessSteps> postProcessing) throws IOException { return importFile(filename, postProcessing, null); } /** * Imports a file via assimp. * * @param filename the file to import * @param postProcessing post processing flags * @param ioSystem ioSystem to load files, or null for default * @return the loaded scene, or null if an error occurred * @throws IOException if an error occurs */ public static AiScene importFile(String filename, Set<AiPostProcessSteps> postProcessing, AiIOSystem<?> ioSystem) throws IOException { return importFile(filename, postProcessing, ioSystem, null); } /** * Imports a file via assimp. * * @param filename the file to import * @param postProcessing post processing flags * @param ioSystem ioSystem to load files, or null for default * @return the loaded scene, or null if an error occurred * @throws IOException if an error occurs */ public static AiScene importFile(String filename, Set<AiPostProcessSteps> postProcessing, AiIOSystem<?> ioSystem, AiProgressHandler progressHandler) throws IOException { loadLibrary(); return aiImportFile(filename, AiPostProcessSteps.toRawValue( postProcessing), ioSystem, progressHandler); } /** * Returns the size of a struct or ptimitive.<p> * * @return the result of sizeof call */ public static native int getVKeysize(); /** * @see #getVKeysize */ public static native int getQKeysize(); /** * @see #getVKeysize */ public static native int getV3Dsize(); /** * @see #getVKeysize */ public static native int getfloatsize(); /** * @see #getVKeysize */ public static native int getintsize(); /** * @see #getVKeysize */ public static native int getuintsize(); /** * @see #getVKeysize */ public static native int getdoublesize(); /** * @see #getVKeysize */ public static native int getlongsize(); /** * Returns a human readable error description.<p> * * This method can be called when one of the import methods fails, i.e., * throws an exception, to get a human readable error description. * * @return the error string */ public static native String getErrorString(); /** * Returns the active wrapper provider.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers). * * @return the active wrapper provider */ public static AiWrapperProvider<?, ?, ?, ?, ?> getWrapperProvider() { return s_wrapperProvider; } /** * Sets a new wrapper provider.<p> * * This method is part of the wrapped API (see {@link AiWrapperProvider} * for details on wrappers). * * @param wrapperProvider the new wrapper provider */ public static void setWrapperProvider(AiWrapperProvider<?, ?, ?, ?, ?> wrapperProvider) { s_wrapperProvider = wrapperProvider; } public static void setLibraryLoader(JassimpLibraryLoader libraryLoader) { s_libraryLoader = libraryLoader; } /** * Helper method for wrapping a matrix.<p> * * Used by JNI, do not modify! * * @param data the matrix data * @return the wrapped matrix */ static Object wrapMatrix(float[] data) { return s_wrapperProvider.wrapMatrix4f(data); } /** * Helper method for wrapping a color (rgb).<p> * * Used by JNI, do not modify! * * @param red red component * @param green green component * @param blue blue component * @return the wrapped color */ static Object wrapColor3(float red, float green, float blue) { return wrapColor4(red, green, blue, 1.0f); } /** * Helper method for wrapping a color (rgba).<p> * * Used by JNI, do not modify! * * @param red red component * @param green green component * @param blue blue component * @param alpha alpha component * @return the wrapped color */ static Object wrapColor4(float red, float green, float blue, float alpha) { ByteBuffer temp = ByteBuffer.allocate(4 * 4); temp.putFloat(red); temp.putFloat(green); temp.putFloat(blue); temp.putFloat(alpha); temp.flip(); return s_wrapperProvider.wrapColor(temp, 0); } /** * Helper method for wrapping a vector.<p> * * Used by JNI, do not modify! * * @param x x component * @param y y component * @param z z component * @return the wrapped vector */ static Object wrapVec3(float x, float y, float z) { ByteBuffer temp = ByteBuffer.allocate(3 * 4); temp.putFloat(x); temp.putFloat(y); temp.putFloat(z); temp.flip(); return s_wrapperProvider.wrapVector3f(temp, 0, 3); } /** * Helper method for wrapping a scene graph node.<p> * * Used by JNI, do not modify! * * @param parent the parent node * @param matrix the transformation matrix * @param meshRefs array of matrix references * @param name the name of the node * @return the wrapped matrix */ static Object wrapSceneNode(Object parent, Object matrix, int[] meshRefs, String name) { return s_wrapperProvider.wrapSceneNode(parent, matrix, meshRefs, name); } /** * Helper method to load the library using the provided JassimpLibraryLoader.<p> * * Synchronized to avoid race conditions. */ private static void loadLibrary() { if(!s_libraryLoaded) { synchronized(s_libraryLoadingLock) { if(!s_libraryLoaded) { s_libraryLoader.loadLibrary(); NATIVE_AIVEKTORKEY_SIZE = getVKeysize(); NATIVE_AIQUATKEY_SIZE = getQKeysize(); NATIVE_AIVEKTOR3D_SIZE = getV3Dsize(); NATIVE_FLOAT_SIZE = getfloatsize(); NATIVE_INT_SIZE = getintsize(); NATIVE_UINT_SIZE = getuintsize(); NATIVE_DOUBLE_SIZE = getdoublesize(); NATIVE_LONG_SIZE = getlongsize(); s_libraryLoaded = true; } } } } /** * Pure static class, no accessible constructor. */ private Jassimp() { /* nothing to do */ } public static int NATIVE_AIVEKTORKEY_SIZE; public static int NATIVE_AIQUATKEY_SIZE; public static int NATIVE_AIVEKTOR3D_SIZE; public static int NATIVE_FLOAT_SIZE; public static int NATIVE_INT_SIZE; public static int NATIVE_UINT_SIZE; public static int NATIVE_DOUBLE_SIZE; public static int NATIVE_LONG_SIZE; }
12,142
29.131514
87
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/JassimpConfig.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Global configuration values (limits). */ public final class JassimpConfig { /** * Maximum number of vertex color sets. */ public static final int MAX_NUMBER_COLORSETS = 8; /** * Maximum number of texture coordinate sets. */ public static final int MAX_NUMBER_TEXCOORDS = 8; /** * Pure static class, no accessible constructor. */ private JassimpConfig() { /* nothing to do */ } }
2,319
33.626866
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/JassimpLibraryLoader.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package jassimp; /** * Library loader for the jassimp library.<p> * * The default implementation uses "System.loadLibrary" to * load the jassimp native library. <p> * * Custom implementations should override the loadLibrary() * function. * */ public class JassimpLibraryLoader { /** * Function to load the native jassimp library. * * Called the first time Jassimp.importFile() is * called. */ public void loadLibrary() { System.loadLibrary("jassimp"); } }
2,339
34.454545
75
java
assimp
assimp-master/port/jassimp/jassimp/src/jassimp/package-info.java
/* --------------------------------------------------------------------------- Open Asset Import Library - Java Binding (jassimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ /** * Java binding for the Open Asset Import Library. */ package jassimp;
1,904
40.413043
75
java
grobid
grobid-master/grobid-service/src/test/java/org/grobid/service/process/GrobidRestProcessFilesTest.java
package org.grobid.service.process; import com.squarespace.jersey2.guice.JerseyGuiceUtils; import org.apache.pdfbox.pdmodel.PDDocument; import org.easymock.EasyMock; import org.grobid.core.document.Document; import org.grobid.core.document.DocumentSource; import org.grobid.core.visualization.BlockVisualizer; import org.grobid.core.visualization.CitationsVisualizer; import org.grobid.core.visualization.FigureTableVisualizer; import org.grobid.service.util.GrobidRestUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.ClassloaderWrapper; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; @RunWith(PowerMockRunner.class) @PrepareForTest({CitationsVisualizer.class, BlockVisualizer.class, FigureTableVisualizer.class}) public class GrobidRestProcessFilesTest { static { JerseyGuiceUtils.install((s, serviceLocator) -> null); } DocumentSource documentSourceMock; GrobidRestProcessFiles target; @Before public void setUp() { documentSourceMock = createMock(DocumentSource.class); target = new GrobidRestProcessFiles(); } @Test public void dispatchProcessing_selectionCitation_shouldWork() throws Exception { PowerMock.mockStatic(CitationsVisualizer.class); expect(CitationsVisualizer.annotatePdfWithCitations(anyObject(PDDocument.class), anyObject(Document.class), anyObject(List.class))).andReturn(null); PowerMock.replay(CitationsVisualizer.class); target.dispatchProcessing(GrobidRestUtils.Annotation.CITATION, null, null, null); PowerMock.verify(CitationsVisualizer.class); } @Test public void dispatchProcessing_selectionBlock_shouldWork() throws Exception { PowerMock.mockStatic(BlockVisualizer.class); expect(BlockVisualizer.annotateBlocks((PDDocument) anyObject(), EasyMock.<File>anyObject(), EasyMock.<Document>anyObject(), anyBoolean(), anyBoolean(), anyBoolean())).andReturn(null); File fakeFile = File.createTempFile("justForTheTest", "baomiao"); fakeFile.deleteOnExit(); expect(documentSourceMock.getXmlFile()).andReturn(fakeFile); PowerMock.replay(BlockVisualizer.class); replay(documentSourceMock); target.dispatchProcessing(GrobidRestUtils.Annotation.BLOCK, null, documentSourceMock, null); PowerMock.verify(BlockVisualizer.class); verify(documentSourceMock); } @Test public void dispatchProcessing_selectionFigure_shouldWork() throws Exception { PowerMock.mockStatic(FigureTableVisualizer.class); File fakeFile = File.createTempFile("justForTheTest", "baomiao"); fakeFile.deleteOnExit(); expect(FigureTableVisualizer.annotateFigureAndTables(anyObject(), EasyMock.anyObject(), EasyMock.anyObject(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean())) .andReturn(null); expect(documentSourceMock.getXmlFile()).andReturn(fakeFile); PowerMock.replay(FigureTableVisualizer.class); replay(documentSourceMock); target.dispatchProcessing(GrobidRestUtils.Annotation.FIGURE, null, documentSourceMock, null); PowerMock.verify(FigureTableVisualizer.class); verify(documentSourceMock); } }
3,732
35.598039
156
java
grobid
grobid-master/grobid-service/src/test/java/org/grobid/service/util/GrobidRestUtilsTest.java
package org.grobid.service.util; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; /** * Created by lfoppiano on 30/11/16. */ public class GrobidRestUtilsTest { @Test public void getAnnotationFor_validType_shouldWork() throws Exception { assertThat(GrobidRestUtils.getAnnotationFor(1), is(GrobidRestUtils.Annotation.BLOCK)); assertThat(GrobidRestUtils.getAnnotationFor(2), is(GrobidRestUtils.Annotation.FIGURE)); assertThat(GrobidRestUtils.getAnnotationFor(0), is(GrobidRestUtils.Annotation.CITATION)); } @Test public void getAnnotationFor_invalidType_shouldWork() throws Exception { assertNull(GrobidRestUtils.getAnnotationFor(-1)); assertNull(GrobidRestUtils.getAnnotationFor(4)); assertNull(GrobidRestUtils.getAnnotationFor(3)); } }
917
33
97
java
grobid
grobid-master/grobid-service/src/test/java/org/grobid/service/tests/GrobidRestServiceTest.java
/* * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package org.grobid.service.tests; import com.google.inject.Guice; import com.squarespace.jersey2.guice.JerseyGuiceUtils; import io.dropwizard.testing.junit.DropwizardAppRule; import org.apache.commons.io.FileUtils; import org.glassfish.jersey.client.JerseyClientBuilder; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.media.multipart.file.FileDataBodyPart; import org.grobid.core.utilities.GrobidProperties; import org.grobid.service.GrobidPaths; import org.grobid.service.GrobidRestService; import org.grobid.service.GrobidServiceConfiguration; import org.grobid.service.main.GrobidServiceApplication; import org.grobid.service.module.GrobidServiceModuleTest; import org.grobid.service.util.BibTexMediaType; import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.core.Form; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import java.io.File; import java.io.IOException; import static org.junit.Assert.*; /** * Tests the RESTful service of the grobid-service project. This class can also * tests a remote system, when setting system property * org.grobid.service.test.uri to host to test. * * @author Florian Zipser */ public class GrobidRestServiceTest { private static final Logger LOGGER = LoggerFactory.getLogger(GrobidRestServiceTest.class); @BeforeClass public static void setInitialContext() throws Exception { } @AfterClass public static void destroyInitialContext() throws Exception { } @ClassRule public static DropwizardAppRule<GrobidServiceConfiguration> APP = new DropwizardAppRule<>(GrobidServiceApplication.class, GrobidServiceModuleTest.TEST_CONFIG_FILE); private String baseUrl() { return String.format("http://localhost:%d%s" + "api/", APP.getLocalPort(), APP.getEnvironment().getApplicationContext().getContextPath()); } @Before public void setUp() throws IOException { JerseyGuiceUtils.reset(); GrobidServiceModuleTest testWorkerModule = new GrobidServiceModuleTest() { // redefine methods that are needed: }; Guice.createInjector(testWorkerModule).injectMembers(this); } private static File getResourceDir() { return (new File("./src/test/resources/")); } private static Client getClient() { Client client = new JerseyClientBuilder().build(); client.register(MultiPartFeature.class); return client; } /** * test the synchronous fully state less rest call */ @Test public void testFullyRestLessHeaderDocument() throws Exception { String resp = getStrResponse(sample4(), GrobidPaths.PATH_HEADER); assertNotNull(resp); } /* * Test the synchronous fully state less rest call */ @Test public void testFullyRestLessFulltextDocument() throws Exception { String resp = getStrResponse(sample4(), GrobidPaths.PATH_FULL_TEXT); assertNotNull(resp); } /** * Test the synchronous state less rest call for dates */ @Test public void testRestDate() throws Exception { String resp = getStrResponse("date", "November 14 1999", GrobidPaths.PATH_DATE); assertNotNull(resp); } /** * Test the synchronous state less rest call for author sequences in headers */ @Test public void testRestNamesHeader() throws Exception { String names = "Ahmed Abu-Rayyan *,a, Qutaiba Abu-Salem b, Norbert Kuhn * ,b, Cäcilia Maichle-Mößmer b"; String resp = getStrResponse("names", names, GrobidPaths.PATH_HEADER_NAMES); assertNotNull(resp); } /** * Test the synchronous state less rest call for author sequences in * citations */ @Test public void testRestNamesCitations() throws Exception { String names = "Marc Shapiro and Susan Horwitz"; String resp = getStrResponse("names", names, GrobidPaths.PATH_CITE_NAMES); assertNotNull(resp); } /** * Test the synchronous state less rest call for affiliation + address * blocks */ @Test public void testRestAffiliations() throws Exception { String affiliations = "Atomic Physics Division, Department of Atomic Physics and Luminescence, " + "Faculty of Applied Physics and Mathematics, Gdansk University of " + "Technology, Narutowicza 11/12, 80-233 Gdansk, Poland"; String resp = getStrResponse("affiliations", affiliations, GrobidPaths.PATH_AFFILIATION); assertNotNull(resp); } /** * Test the synchronous state less rest call for patent citation extraction. * Send all xml and xml.gz ST36 files found in a given folder test/resources/patent * to the web service and write back the results in the test/sample */ @Test @Ignore public void testRestPatentCitation() throws Exception { Client client = getClient(); File xmlDirectory = new File(getResourceDir().getAbsoluteFile() + "/patent"); File[] files = xmlDirectory.listFiles(); assertNotNull(files); for (final File currXML : files) { try { if (currXML.getName().toLowerCase().endsWith(".xml") || currXML.getName().toLowerCase().endsWith(".xml.gz")) { assertTrue("Cannot run the test, because the sample file '" + currXML + "' does not exists.", currXML.exists()); FormDataMultiPart form = new FormDataMultiPart(); form.field("input", currXML, MediaType.MULTIPART_FORM_DATA_TYPE); form.field("consolidate", "0", MediaType.MULTIPART_FORM_DATA_TYPE); Response response = client.target( baseUrl() + GrobidPaths.PATH_CITATION_PATENT_ST36) .request() .accept(MediaType.APPLICATION_XML + ";charset=utf-8") .post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA_TYPE)); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String tei = response.readEntity(String.class); File outputFile = new File(getResourceDir().getAbsoluteFile() + "/../sample/" + currXML.getName().replace(".xml", ".tei.xml").replace(".gz", "")); // writing the result in the sample directory FileUtils.writeStringToFile(outputFile, tei, "UTF-8"); } } catch (final Exception exp) { LOGGER.error("An error occured while processing the file " + currXML.getAbsolutePath() + ". Continuing the process for the other files"); } } } @Test public void testGetVersion_shouldReturnCurrentGrobidVersion() throws Exception { Response resp = getClient().target(baseUrl() + GrobidPaths.PATH_GET_VERSION) .request() .get(); assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus()); assertEquals(GrobidProperties.getVersion(), resp.readEntity(String.class)); } @Test public void isAliveReturnsTrue() throws Exception { Response resp = getClient().target(baseUrl() + GrobidPaths.PATH_IS_ALIVE) .request() .get(); assertEquals(Response.Status.OK.getStatusCode(), resp.getStatus()); assertEquals("true", resp.readEntity(String.class)); } @Test public void processCitationReturnsCorrectBibTeXForMissingFirstName() { Form form = new Form(); form.param(GrobidRestService.CITATION, "Graff, Expert. Opin. Ther. Targets (2002) 6(1): 103-113"); Response response = getClient().target(baseUrl()).path(GrobidPaths.PATH_CITATION) .request() .accept(BibTexMediaType.MEDIA_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("@article{-1,\n" + " author = {Graff},\n" + " journal = {Expert. Opin. Ther. Targets},\n" + " date = {2002},\n" + " year = {2002},\n" + " pages = {103--113},\n" + " volume = {6},\n" + " number = {1}\n" + "}\n", response.readEntity(String.class)); } @Test public void processCitationReturnsBibTeX() { Form form = new Form(); form.param(GrobidRestService.CITATION, "Kolb, S., Wirtz G.: Towards Application Portability in Platform as a Service\n" + "Proceedings of the 8th IEEE International Symposium on Service-Oriented System Engineering (SOSE), Oxford, United Kingdom, April 7 - 10, 2014."); Response response = getClient().target(baseUrl()).path(GrobidPaths.PATH_CITATION) .request() .accept(BibTexMediaType.MEDIA_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("@inproceedings{-1,\n" + " author = {Kolb, S and Wirtz, G},\n" + " booktitle = {Towards Application Portability in Platform as a Service Proceedings of the 8th IEEE International Symposium on Service-Oriented System Engineering (SOSE)},\n" + " date = {2014},\n" + " year = {2014},\n" + // " year = {April 7 - 10, 2014},\n" + " address = {Oxford, United Kingdom}\n" + "}\n", response.readEntity(String.class)); } @Test public void processCitationReturnsBibTeXAndCanInludeRaw() { Form form = new Form(); form.param(GrobidRestService.CITATION, "Kolb, S., Wirtz G.: Towards Application Portability in Platform as a Service\n" + "Proceedings of the 8th IEEE International Symposium on Service-Oriented System Engineering (SOSE), Oxford, United Kingdom, April 7 - 10, 2014."); form.param(GrobidRestService.INCLUDE_RAW_CITATIONS, "1"); Response response = getClient().target(baseUrl()).path(GrobidPaths.PATH_CITATION) .request() .accept(BibTexMediaType.MEDIA_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("@inproceedings{-1,\n" + " author = {Kolb, S and Wirtz, G},\n" + " booktitle = {Towards Application Portability in Platform as a Service Proceedings of the 8th IEEE International Symposium on Service-Oriented System Engineering (SOSE)},\n" + " date = {2014},\n" + " year = {2014},\n" + // " year = {April 7 - 10, 2014},\n" + " address = {Oxford, United Kingdom},\n" + " raw = {Kolb, S., Wirtz G.: Towards Application Portability in Platform as a Service\n" + "Proceedings of the 8th IEEE International Symposium on Service-Oriented System Engineering (SOSE), Oxford, United Kingdom, April 7 - 10, 2014.}\n" + "}\n", response.readEntity(String.class)); } @Ignore public void processStatelessReferencesDocumentReturnsValidBibTeXForKolbAndKopp() throws Exception { final FileDataBodyPart filePart = new FileDataBodyPart(GrobidRestService.INPUT, new File(this.getClass().getResource("/sample5/gadr.pdf").toURI())); FormDataMultiPart formDataMultiPart = new FormDataMultiPart(); //final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.field("foo", "bar").bodyPart(filePart); final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart.bodyPart(filePart); Response response = getClient().target(baseUrl() + GrobidPaths.PATH_REFERENCES) .request(BibTexMediaType.MEDIA_TYPE) .post(Entity.entity(multipart, multipart.getMediaType())); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); assertEquals("@techreport{0,\n" + " author = {Büchler, A},\n" + " year = {2017}\n" + "}\n" + "\n" + "@article{1,\n" + " author = {Kopp, O and Armbruster, A and Zimmermann, O},\n" + " title = {Markdown Architectural Decision Records: Format and Tool Support},\n" + " booktitle = {ZEUS. CEUR Workshop Proceedings},\n" + " year = {2018},\n" + " volume = {2072}\n" + "}\n" + "\n" + "@article{2,\n" + " author = {Thurimella, A and Schubanz, M and Pleuss, A and Botterweck, G},\n" + " title = {Guidelines for Managing Requirements Rationales},\n" + " journal = {IEEE Software},\n" + " year = {Jan 2017},\n" + " pages = {82--90},\n" + " volume = {34},\n" + " number = {1}\n" + "}\n" + "\n" + "@article{3,\n" + " author = {Zdun, U and Capilla, R and Tran, H and Zimmermann, O},\n" + " title = {Sustainable Architectural Design Decisions},\n" + " journal = {IEEE Software},\n" + " year = {Nov 2013},\n" + " pages = {46--53},\n" + " volume = {30},\n" + " number = {6}\n" + "}\n" + "\n" + "@inbook{4,\n" + " author = {Zimmermann, O and Wegmann, L and Koziolek, H and Goldschmidt, T},\n" + " title = {Architectural Decision Guidance Across Projects -Problem Space Modeling, Decision Backlog Management and Cloud Computing Knowledge},\n" + " booktitle = {Working IEEE/IFIP Conference on Software Architecture},\n" + " year = {2015}\n" + "}\n" + "\n" + "@inbook{5,\n" + " author = {Zimmermann, O and Miksovic, C},\n" + " title = {Decisions required vs. decisions made},\n" + " booktitle = {Aligning Enterprise, System, and Software Architectures},\n" + " publisher = {IGI Global},\n" + " year = {2013}\n" + "}\n" + "\n", response.readEntity(String.class)); } private String getStrResponse(File pdf, String method) { assertTrue("Cannot run the test, because the sample file '" + pdf + "' does not exists.", pdf.exists()); FormDataMultiPart form = new FormDataMultiPart(); form.field("input", pdf, MediaType.MULTIPART_FORM_DATA_TYPE); form.field("consolidate", "0", MediaType.MULTIPART_FORM_DATA_TYPE); Response response = getClient().target(baseUrl() + method) .request() .post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA)); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String cont = response.readEntity(String.class); return cont; } private String getStrResponse(String key, String val, String method) { MultivaluedMap<String, String> formData = new MultivaluedHashMap<>(); formData.add(key, val); Response response = getClient().target(baseUrl() + method) .request() .post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED)); assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); String postResp = response.readEntity(String.class); assertNotNull(postResp); return postResp; } private static File sample4() { return new File(getResourceDir().getAbsoluteFile() + "/sample4/sample.pdf"); } }
17,148
42.747449
193
java
grobid
grobid-master/grobid-service/src/test/java/org/grobid/service/module/GrobidServiceModuleTest.java
package org.grobid.service.module; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Binder; import com.google.inject.Provides; import com.google.inject.Singleton; import io.dropwizard.configuration.ConfigurationFactory; import io.dropwizard.configuration.DefaultConfigurationFactoryFactory; import io.dropwizard.configuration.FileConfigurationSourceProvider; import io.dropwizard.jackson.Jackson; import io.dropwizard.setup.Environment; import org.grobid.service.GrobidServiceConfiguration; import org.grobid.service.modules.GrobidServiceModule; import org.hibernate.validator.HibernateValidator; import javax.validation.Validation; import javax.validation.ValidatorFactory; public class GrobidServiceModuleTest extends GrobidServiceModule { public static final String TEST_CONFIG_FILE = "src/test/resources/setup/config/test-config.yaml"; public GrobidServiceModuleTest() { super(); } @Override public void configure(Binder binder) { super.configure(binder); } @Provides @Singleton @Override public GrobidServiceConfiguration getConfiguration() { ObjectMapper objectMapper = Jackson.newObjectMapper(); ValidatorFactory validatorFactory = Validation .byProvider(HibernateValidator.class) .configure() // .addValidatedValueHandler(new OptionalValidatedValueUnwrapper()) .buildValidatorFactory(); final ConfigurationFactory<GrobidServiceConfiguration> configurationFactory = new DefaultConfigurationFactoryFactory<GrobidServiceConfiguration>() .create(GrobidServiceConfiguration.class, validatorFactory.getValidator(), objectMapper, "dw"); try { return configurationFactory.build(new FileConfigurationSourceProvider(), TEST_CONFIG_FILE); } catch (Exception e) { throw new RuntimeException(e); } } @Override @Provides protected Environment getEnvironment() { return new Environment("test-grobid-service-env", new ObjectMapper(), null, new MetricRegistry(), this.getClass().getClassLoader()); } }
2,286
33.134328
105
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/GrobidPaths.java
package org.grobid.service; /** * This interface only contains the path extensions for accessing the grobid service. * */ public interface GrobidPaths { /** * path extension for grobid service. */ String PATH_GROBID = "/"; /** * path extension for grobid adm. */ String PATH_ADM = "/adm"; /** * path extension for is alive request. */ String PATH_IS_ALIVE = "isalive"; /** * path extension for grobid admin pages. */ //String PATH_ADMIN = "admin"; /** * path extension for processing document headers. */ String PATH_HEADER = "processHeaderDocument"; /** * path extension for processing document headers HTML. */ String PATH_HEADER_HTML = "processHeaderDocumentHTML"; /** * path extension for processing full text of documents. */ String PATH_FULL_TEXT = "processFulltextDocument"; /** * path extension for processing full text of documents together with image extraction. */ String PATH_FULL_TEXT_ASSET = "processFulltextAssetDocument"; /** * path extension for processing full text of documents. */ String PATH_FULL_TEXT_HTML = "processFulltextDocumentHTML"; /** * path extension for processing dates. */ String PATH_DATE = "processDate"; /** * path extension for processing names in header parts of documents headers. */ String PATH_HEADER_NAMES = "processHeaderNames"; /** * path extension for processing citation in patent documents in TEI. */ //String PATH_CITATION_PATENT_TEI = "processCitationPatentTEI"; /** * path extension for processing citation in patent documents in ST.36. */ String PATH_CITATION_PATENT_ST36 = "processCitationPatentST36"; /** * path extension for processing citation in patent documents in PDF. */ String PATH_CITATION_PATENT_PDF = "processCitationPatentPDF"; /** * path extension for processing citation in patent documents in utf-8 txt . */ String PATH_CITATION_PATENT_TXT = "processCitationPatentTXT"; /** * path extension for processing citation annotations. */ //String PATH_CITATION_ANNOTATION = "processCitationPatentTEI"; /** * path extension for processing names as appearing in a citation (e.g. bibliographic section). */ String PATH_CITE_NAMES = "processCitationNames"; /** * path extension for processing affiliation in document headers. */ String PATH_AFFILIATION = "processAffiliations"; /** * path extension for processing isolated citation. */ String PATH_CITATION = "processCitation"; /** * path extension for processing a list of isolated citations. */ String PATH_CITATION_LIST = "processCitationList"; /** * path extension for processing all the references in a PDF file. */ String PATH_REFERENCES = "processReferences"; /** * path extension for processing and annotating a PDF file. */ String PATH_PDF_ANNOTATION = "annotatePDF"; /** * path extension for the JSON annotations of the bibliographical references in a PDF file. */ String PATH_REFERENCES_PDF_ANNOTATION = "referenceAnnotations"; /** * path extension for the JSON annotations of the citations in a patent PDF file. */ String PATH_CITATIONS_PATENT_PDF_ANNOTATION = "citationPatentAnnotations"; /** * path extension for processing sha1. */ String PATH_SHA1 = "sha1"; /** * path extension for getting all properties. */ String PATH_ALL_PROPS = "allProperties"; /** * path extension to update property value. */ String PATH_CHANGE_PROPERTY_VALUE = "changePropertyValue"; /** * path extension for getting version */ String PATH_GET_VERSION = "version"; /** * path to retrieve a model */ String PATH_MODEL = "model"; /** * path for launching the training of a model */ String PATH_MODEL_TRAINING = "modelTraining"; /** * path for getting the advancement of the training of a model or * the evaluation metrics of the new model if the training is completed */ String PATH_TRAINING_RESULT = "trainingResult"; }
3,948
23.079268
96
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/GrobidRestService.java
package org.grobid.service; import com.codahale.metrics.annotation.Timed; import com.google.inject.Inject; import com.google.inject.Singleton; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataParam; import org.grobid.core.engines.config.GrobidAnalysisConfig; import org.grobid.core.factory.AbstractEngineFactory; import org.grobid.core.utilities.GrobidProperties; import org.grobid.core.engines.Engine; import org.grobid.core.factory.GrobidPoolingFactory; import org.grobid.service.process.GrobidRestProcessFiles; import org.grobid.service.process.GrobidRestProcessGeneric; import org.grobid.service.process.GrobidRestProcessString; import org.grobid.service.process.GrobidRestProcessTraining; import org.grobid.service.util.BibTexMediaType; import org.grobid.service.util.ExpectedResponseType; import org.grobid.service.util.GrobidRestUtils; import org.grobid.service.util.ZipUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.*; import javax.ws.rs.core.*; import java.io.File; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; /** * RESTful service for the GROBID system. * */ @Timed @Singleton @Path(GrobidPaths.PATH_GROBID) public class GrobidRestService implements GrobidPaths { private static final Logger LOGGER = LoggerFactory.getLogger(GrobidRestService.class); private static final String NAMES = "names"; private static final String DATE = "date"; private static final String AFFILIATIONS = "affiliations"; public static final String CITATION = "citations"; // private static final String TEXT = "text"; private static final String SHA1 = "sha1"; private static final String XML = "xml"; public static final String INPUT = "input"; public static final String CONSOLIDATE_CITATIONS = "consolidateCitations"; public static final String CONSOLIDATE_HEADER = "consolidateHeader"; public static final String INCLUDE_RAW_AFFILIATIONS = "includeRawAffiliations"; public static final String INCLUDE_RAW_CITATIONS = "includeRawCitations"; public static final String INCLUDE_FIGURES_TABLES = "includeFiguresTables"; @Inject private GrobidRestProcessFiles restProcessFiles; @Inject private GrobidRestProcessGeneric restProcessGeneric; @Inject private GrobidRestProcessString restProcessString; @Inject private GrobidRestProcessTraining restProcessTraining; @Inject public GrobidRestService(GrobidServiceConfiguration configuration) { GrobidProperties.setGrobidHome(new File(configuration.getGrobid().getGrobidHome()).getAbsolutePath()); /*if (configuration.getGrobid().getGrobidProperties() != null) { GrobidProperties.setGrobidPropertiesPath(new File(configuration.getGrobid().getGrobidProperties()).getAbsolutePath()); } else { GrobidProperties.setGrobidPropertiesPath(new File(configuration.getGrobid().getGrobidHome(), "/config/grobid.properties").getAbsolutePath()); }*/ GrobidProperties.getInstance(); GrobidProperties.setContextExecutionServer(true); LOGGER.info("Initiating Servlet GrobidRestService"); AbstractEngineFactory.init(); Engine engine = null; try { // this will init or not all the models in memory engine = Engine.getEngine(configuration.getGrobid().getModelPreload()); } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time."); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs when initiating the grobid engine. ", exp); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.info("Initiating of Servlet GrobidRestService finished."); } /** * @see org.grobid.service.process.GrobidRestProcessGeneric#isAlive() */ @Path(GrobidPaths.PATH_IS_ALIVE) @Produces(MediaType.TEXT_PLAIN) @GET public Response isAlive() { return Response.status(Response.Status.OK).entity(restProcessGeneric.isAlive()).build(); } /** * @see org.grobid.service.process.GrobidRestProcessGeneric#getVersion() */ @Path(GrobidPaths.PATH_GET_VERSION) @Produces(MediaType.TEXT_PLAIN) @GET public Response getVersion() { return restProcessGeneric.getVersion(); } /** * @see org.grobid.service.process.GrobidRestProcessGeneric#getDescription_html(UriInfo) */ @Produces(MediaType.TEXT_HTML) @GET @Path("grobid") public Response getDescription_html(@Context UriInfo uriInfo) { return restProcessGeneric.getDescription_html(uriInfo); } /** * @see org.grobid.service.process.GrobidRestProcessAdmin#getAdminParams(String) */ /*@Path(PATH_ADMIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_HTML) @POST public Response getAdmin_htmlPost(@FormParam(SHA1) String sha1) { return restProcessAdmin.getAdminParams(sha1); }*/ /** * @see org.grobid.service.process.GrobidRestProcessAdmin#getAdminParams(String) */ /*@Path(PATH_ADMIN) @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_HTML) @GET public Response getAdmin_htmlGet(@QueryParam(SHA1) String sha1) { return restProcessAdmin.getAdminParams(sha1); }*/ @Path(PATH_HEADER) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @POST public Response processHeaderDocumentReturnXml_post( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations) { int consol = validateConsolidationParam(consolidate); return restProcessFiles.processStatelessHeaderDocument( inputStream, consol, validateIncludeRawParam(includeRawAffiliations), ExpectedResponseType.XML ); } @Path(PATH_HEADER) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @PUT public Response processStatelessHeaderDocumentReturnXml( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations) { return processHeaderDocumentReturnXml_post(inputStream, consolidate, includeRawAffiliations); } @Path(PATH_HEADER) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(BibTexMediaType.MEDIA_TYPE) @POST public Response processHeaderDocumentReturnBibTeX_post( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations) { int consol = validateConsolidationParam(consolidate); return restProcessFiles.processStatelessHeaderDocument( inputStream, consol, validateIncludeRawParam(includeRawAffiliations), ExpectedResponseType.BIBTEX ); } @Path(PATH_HEADER) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(BibTexMediaType.MEDIA_TYPE) @PUT public Response processStatelessHeaderDocumentReturnBibTeX( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations) { return processHeaderDocumentReturnBibTeX_post(inputStream, consolidate, includeRawAffiliations); } @Path(PATH_FULL_TEXT) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @POST public Response processFulltextDocument_post( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidateHeader, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidateCitations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations, @DefaultValue("-1") @FormDataParam("start") int startPage, @DefaultValue("-1") @FormDataParam("end") int endPage, @FormDataParam("generateIDs") String generateIDs, @FormDataParam("segmentSentences") String segmentSentences, @FormDataParam("teiCoordinates") List<FormDataBodyPart> coordinates) throws Exception { return processFulltext( inputStream, consolidateHeader, consolidateCitations, includeRawAffiliations, includeRawCitations, startPage, endPage, generateIDs, segmentSentences, coordinates ); } @Path(PATH_FULL_TEXT) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @PUT public Response processFulltextDocument( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidateHeader, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidateCitations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations, @DefaultValue("-1") @FormDataParam("start") int startPage, @DefaultValue("-1") @FormDataParam("end") int endPage, @FormDataParam("generateIDs") String generateIDs, @FormDataParam("segmentSentences") String segmentSentences, @FormDataParam("teiCoordinates") List<FormDataBodyPart> coordinates) throws Exception { return processFulltext( inputStream, consolidateHeader, consolidateCitations, includeRawAffiliations, includeRawCitations, startPage, endPage, generateIDs, segmentSentences, coordinates ); } private Response processFulltext(InputStream inputStream, String consolidateHeader, String consolidateCitations, String includeRawAffiliations, String includeRawCitations, int startPage, int endPage, String generateIDs, String segmentSentences, List<FormDataBodyPart> coordinates ) throws Exception { int consolHeader = validateConsolidationParam(consolidateHeader); int consolCitations = validateConsolidationParam(consolidateCitations); boolean includeRaw = validateIncludeRawParam(includeRawCitations); boolean generate = validateGenerateIdParam(generateIDs); boolean segment = validateGenerateIdParam(segmentSentences); List<String> teiCoordinates = collectCoordinates(coordinates); return restProcessFiles.processFulltextDocument( inputStream, consolHeader, consolCitations, validateIncludeRawParam(includeRawAffiliations), includeRaw, startPage, endPage, generate, segment, teiCoordinates ); } private List<String> collectCoordinates(List<FormDataBodyPart> coordinates) { List<String> teiCoordinates = new ArrayList<>(); if (coordinates != null) { for (FormDataBodyPart coordinate : coordinates) { String v = coordinate.getValueAs(String.class); teiCoordinates.add(v); } } return teiCoordinates; } private boolean validateGenerateIdParam(String generateIDs) { boolean generate = false; if ((generateIDs != null) && (generateIDs.equals("1") || generateIDs.equals("true"))) { generate = true; } return generate; } private boolean validateIncludeRawParam(String includeRaw) { return ((includeRaw != null) && (includeRaw.equals("1") || includeRaw.equals("true"))); } private int validateConsolidationParam(String consolidate) { int consol = 0; if (consolidate != null) { try { consol = Integer.parseInt(consolidate); } catch(Exception e) { LOGGER.warn("Invalid consolidation parameter (should be an integer): " + consolidate, e); } } return consol; } @Path(PATH_FULL_TEXT_ASSET) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/zip") @POST public Response processFulltextAssetDocument_post( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidateHeader, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidateCitations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations, @DefaultValue("-1") @FormDataParam("start") int startPage, @DefaultValue("-1") @FormDataParam("end") int endPage, @FormDataParam("generateIDs") String generateIDs, @FormDataParam("segmentSentences") String segmentSentences, @FormDataParam("teiCoordinates") List<FormDataBodyPart> coordinates) throws Exception { return processStatelessFulltextAssetHelper( inputStream, consolidateHeader, consolidateCitations, includeRawAffiliations, includeRawCitations, startPage, endPage, generateIDs, segmentSentences, coordinates ); } @Path(PATH_FULL_TEXT_ASSET) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/zip") @PUT public Response processStatelessFulltextAssetDocument( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidateHeader, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidateCitations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations, @DefaultValue("-1") @FormDataParam("start") int startPage, @DefaultValue("-1") @FormDataParam("end") int endPage, @FormDataParam("generateIDs") String generateIDs, @FormDataParam("segmentSentences") String segmentSentences, @FormDataParam("teiCoordinates") List<FormDataBodyPart> coordinates) throws Exception { return processStatelessFulltextAssetHelper( inputStream, consolidateHeader, consolidateCitations, includeRawAffiliations, includeRawCitations, startPage, endPage, generateIDs, segmentSentences, coordinates ); } private Response processStatelessFulltextAssetHelper(InputStream inputStream, String consolidateHeader, String consolidateCitations, String includeRawAffiliations, String includeRawCitations, int startPage, int endPage, String generateIDs, String segmentSentences, List<FormDataBodyPart> coordinates) throws Exception { int consolHeader = validateConsolidationParam(consolidateHeader); int consolCitations = validateConsolidationParam(consolidateCitations); boolean includeRaw = validateIncludeRawParam(includeRawCitations); boolean generate = validateGenerateIdParam(generateIDs); boolean segment = validateGenerateIdParam(segmentSentences); List<String> teiCoordinates = collectCoordinates(coordinates); return restProcessFiles.processStatelessFulltextAssetDocument( inputStream, consolHeader, consolCitations, validateIncludeRawParam(includeRawAffiliations), includeRaw, startPage, endPage, generate, segment, teiCoordinates ); } /*@Path(PATH_CITATION_PATENT_TEI) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @POST public StreamingOutput processCitationPatentTEI(@FormDataParam(INPUT) InputStream pInputStream, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String consolidate) throws Exception { int consol = validateConsolidationParam(consolidate); return restProcessFiles.processCitationPatentTEI(pInputStream, consol); }*/ @Path(PATH_CITATION_PATENT_ST36) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @POST public Response processCitationPatentST36( @FormDataParam(INPUT) InputStream pInputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) throws Exception { int consol = validateConsolidationParam(consolidate); boolean includeRaw = validateIncludeRawParam(includeRawCitations); pInputStream = ZipUtils.decompressStream(pInputStream); return restProcessFiles.processCitationPatentST36(pInputStream, consol, includeRaw); } @Path(PATH_CITATION_PATENT_PDF) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @POST public Response processCitationPatentPDF( @FormDataParam(INPUT) InputStream pInputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) throws Exception { int consol = validateConsolidationParam(consolidate); boolean includeRaw = validateIncludeRawParam(includeRawCitations); return restProcessFiles.processCitationPatentPDF(pInputStream, consol, includeRaw); } @Path(PATH_CITATION_PATENT_TXT) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_XML) @POST public Response processCitationPatentTXT_post( @FormParam(INPUT) String text, @DefaultValue("0") @FormParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { int consol = validateConsolidationParam(consolidate); boolean includeRaw = validateIncludeRawParam(includeRawCitations); return restProcessString.processCitationPatentTXT(text, consol, includeRaw); } /** * @see org.grobid.service.process.GrobidRestProcessString#processDate(String) */ @Path(PATH_DATE) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @POST public Response processDate_post(@FormParam(DATE) String date) { return restProcessString.processDate(date); } /** * @see org.grobid.service.process.GrobidRestProcessString#processDate(String) */ @Path(PATH_DATE) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @PUT public Response processDate(@FormParam(DATE) String date) { return restProcessString.processDate(date); } /** * @see org.grobid.service.process.GrobidRestProcessString#processNamesHeader(String) */ @Path(PATH_HEADER_NAMES) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @POST public Response processNamesHeader_post(@FormParam(NAMES) String names) { return restProcessString.processNamesHeader(names); } /** * @see org.grobid.service.process.GrobidRestProcessString#processNamesHeader(String) */ @Path(PATH_HEADER_NAMES) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @PUT public Response processNamesHeader(@FormParam(NAMES) String names) { return restProcessString.processNamesHeader(names); } /** * @see org.grobid.service.process.GrobidRestProcessString#processNamesCitation(String) */ @Path(PATH_CITE_NAMES) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @POST public Response processNamesCitation_post(@FormParam(NAMES) String names) { return restProcessString.processNamesCitation(names); } /** * @see org.grobid.service.process.GrobidRestProcessString#processNamesCitation(String) */ @Path(PATH_CITE_NAMES) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @PUT public Response processNamesCitation(@FormParam(NAMES) String names) { return restProcessString.processNamesCitation(names); } /** * @see org.grobid.service.process.GrobidRestProcessString#processAffiliations(String) */ @Path(PATH_AFFILIATION) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @POST public Response processAffiliations_post(@FormParam(AFFILIATIONS) String affiliations) { return restProcessString.processAffiliations(affiliations); } /** * @see org.grobid.service.process.GrobidRestProcessString#processAffiliations(String) */ @Path(PATH_AFFILIATION) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @PUT public Response processAffiliations(@FormParam(AFFILIATIONS) String affiliation) { return restProcessString.processAffiliations(affiliation); } @Path(PATH_CITATION) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_XML) @POST public Response processCitationReturnXml_post( @FormParam(CITATION) String citation, @DefaultValue("0") @FormParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { GrobidAnalysisConfig config = new GrobidAnalysisConfig.GrobidAnalysisConfigBuilder() .consolidateCitations(validateConsolidationParam(consolidate)) .includeRawCitations(validateIncludeRawParam(includeRawCitations)) .build(); return restProcessString.processCitation(citation, config, ExpectedResponseType.XML); } @Path(PATH_CITATION) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_XML) @PUT public Response processCitationReturnXml( @FormParam(CITATION) String citation, @DefaultValue("0") @FormParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { return processCitationReturnXml_post(citation, consolidate, includeRawCitations); } @Path(PATH_CITATION) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(BibTexMediaType.MEDIA_TYPE) @POST public Response processCitationReturnBibTeX_post( @FormParam(CITATION) String citation, @DefaultValue("0") @FormParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { GrobidAnalysisConfig config = new GrobidAnalysisConfig.GrobidAnalysisConfigBuilder() .consolidateCitations(validateConsolidationParam(consolidate)) .includeRawCitations(validateIncludeRawParam(includeRawCitations)) .build(); return restProcessString.processCitation(citation, config, ExpectedResponseType.BIBTEX); } @Path(PATH_CITATION) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(BibTexMediaType.MEDIA_TYPE) @PUT public Response processCitationReturnBibTeX( @FormParam(CITATION) String citation, @DefaultValue("0") @FormParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { return processCitationReturnBibTeX_post(citation, consolidate, includeRawCitations); } @Path(PATH_CITATION_LIST) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.APPLICATION_XML) @POST public Response processCitationListReturnXml_post( @FormParam(CITATION) List<String> citations, @DefaultValue("0") @FormParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { GrobidAnalysisConfig config = new GrobidAnalysisConfig.GrobidAnalysisConfigBuilder() .consolidateCitations(validateConsolidationParam(consolidate)) .includeRawCitations(validateIncludeRawParam(includeRawCitations)) .build(); return restProcessString.processCitationList(citations, config, ExpectedResponseType.XML); } @Path(PATH_CITATION_LIST) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(BibTexMediaType.MEDIA_TYPE) @POST public Response processCitationListReturnBibTeX_post( @FormParam(CITATION) List<String> citations, @DefaultValue("0") @FormParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { GrobidAnalysisConfig config = new GrobidAnalysisConfig.GrobidAnalysisConfigBuilder() .consolidateCitations(validateConsolidationParam(consolidate)) .includeRawCitations(validateIncludeRawParam(includeRawCitations)) .build(); return restProcessString.processCitationList(citations, config, ExpectedResponseType.BIBTEX); } /** * @see org.grobid.service.process.GrobidRestProcessAdmin#processSHA1(String) */ /*@Path(PATH_SHA1) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @POST public Response processSHA1Post(@FormParam(SHA1) String sha1) { return restProcessAdmin.processSHA1(sha1); }*/ /** * @see org.grobid.service.process.GrobidRestProcessAdmin#processSHA1(String) */ /*@Path(PATH_SHA1) @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) @GET public Response processSHA1Get(@QueryParam(SHA1) String sha1) { return restProcessAdmin.processSHA1(sha1); }*/ /** * @see org.grobid.service.process.GrobidRestProcessAdmin#getAllPropertiesValues(String) */ /*@Path(PATH_ALL_PROPS) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @POST public Response getAllPropertiesValuesPost(@FormParam(SHA1) String sha1) { return restProcessAdmin.getAllPropertiesValues(sha1); }*/ /** * @see org.grobid.service.process.GrobidRestProcessAdmin#getAllPropertiesValues(String) */ /*@Path(PATH_ALL_PROPS) @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) @GET public Response getAllPropertiesValuesGet(@QueryParam(SHA1) String sha1) { return restProcessAdmin.getAllPropertiesValues(sha1); }*/ /** * @see org.grobid.service.process.GrobidRestProcessAdmin#changePropertyValue(String) */ /*@Path(PATH_CHANGE_PROPERTY_VALUE) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) @POST public Response changePropertyValuePost(@FormParam(XML) String xml) { return restProcessAdmin.changePropertyValue(xml); }*/ /** * @see org.grobid.service.process.GrobidRestProcessAdmin#changePropertyValue(String) */ /*@Path(PATH_CHANGE_PROPERTY_VALUE) @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) @GET public Response changePropertyValueGet(@QueryParam(XML) String xml) { return restProcessAdmin.changePropertyValue(xml); }*/ @Path(PATH_REFERENCES) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @POST public Response processStatelessReferencesDocumentReturnXml_post( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { int consol = validateConsolidationParam(consolidate); boolean includeRaw = validateIncludeRawParam(includeRawCitations); return restProcessFiles.processStatelessReferencesDocument(inputStream, consol, includeRaw, ExpectedResponseType.XML); } @Path(PATH_REFERENCES) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_XML) @PUT public Response processStatelessReferencesDocumentReturnXml( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { return processStatelessReferencesDocumentReturnXml_post(inputStream, consolidate, includeRawCitations); } @Path(PATH_REFERENCES) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(BibTexMediaType.MEDIA_TYPE) @POST public Response processStatelessReferencesDocumentReturnBibTeX_post( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { int consol = validateConsolidationParam(consolidate); boolean includeRaw = validateIncludeRawParam(includeRawCitations); return restProcessFiles.processStatelessReferencesDocument(inputStream, consol, includeRaw, ExpectedResponseType.BIBTEX); } @Path(PATH_REFERENCES) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(BibTexMediaType.MEDIA_TYPE) @PUT public Response processStatelessReferencesDocumentReturnBibTeX( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) { return processStatelessReferencesDocumentReturnBibTeX_post(inputStream, consolidate, includeRawCitations); } @Path(PATH_PDF_ANNOTATION) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/pdf") @POST public Response processAnnotatePDF( @FormDataParam(INPUT) InputStream inputStream, @FormDataParam("name") String fileName, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidateHeader, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidateCitations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_AFFILIATIONS) String includeRawAffiliations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations, @FormDataParam("type") int type) throws Exception { int consolHeader = validateConsolidationParam(consolidateHeader); int consolCitations = validateConsolidationParam(consolidateCitations); boolean includeRaw = validateIncludeRawParam(includeRawCitations); return restProcessFiles.processPDFAnnotation( inputStream, fileName, consolHeader, consolCitations, validateIncludeRawParam(includeRawAffiliations), includeRaw, GrobidRestUtils.getAnnotationFor(type) ); } @Path(PATH_REFERENCES_PDF_ANNOTATION) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/json") @POST public Response processPDFReferenceAnnotation( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_HEADER) String consolidateHeader, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidateCitations, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations, @DefaultValue("0") @FormDataParam(INCLUDE_FIGURES_TABLES) String includeFiguresTables) throws Exception { int consolHeader = validateConsolidationParam(consolidateHeader); int consolCitations = validateConsolidationParam(consolidateCitations); boolean includeRaw = validateIncludeRawParam(includeRawCitations); boolean includeFig = validateIncludeRawParam(includeFiguresTables); return restProcessFiles.processPDFReferenceAnnotation(inputStream, consolHeader, consolCitations, includeRaw, includeFig); } @Path(PATH_CITATIONS_PATENT_PDF_ANNOTATION) @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/json") @POST public Response annotatePDFPatentCitation( @FormDataParam(INPUT) InputStream inputStream, @DefaultValue("0") @FormDataParam(CONSOLIDATE_CITATIONS) String consolidate, @DefaultValue("0") @FormDataParam(INCLUDE_RAW_CITATIONS) String includeRawCitations) throws Exception { int consol = validateConsolidationParam(consolidate); boolean includeRaw = validateIncludeRawParam(includeRawCitations); return restProcessFiles.annotateCitationPatentPDF(inputStream, consol, includeRaw); } public void setRestProcessFiles(GrobidRestProcessFiles restProcessFiles) { this.restProcessFiles = restProcessFiles; } public void setRestProcessGeneric(GrobidRestProcessGeneric restProcessGeneric) { this.restProcessGeneric = restProcessGeneric; } public void setRestProcessString(GrobidRestProcessString restProcessString) { this.restProcessString = restProcessString; } // API for training @Path(PATH_MODEL_TRAINING) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces("application/json") @POST public Response trainModel(@FormParam("model") String model, @DefaultValue("crf") @FormParam("architecture") String architecture, @DefaultValue("split") @FormParam("type") String type, @DefaultValue("0.9") @FormParam("ratio") double ratio, @DefaultValue("10") @FormParam("n") int n, @DefaultValue("0") @FormParam("incremental") String incremental) { boolean incrementalVal = validateIncludeRawParam(incremental); return restProcessTraining.trainModel(model, architecture, type, ratio, n, incrementalVal); } @Path(PATH_TRAINING_RESULT) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces("application/json") @POST public Response resultTraining(@FormParam("token") String token) { return restProcessTraining.resultTraining(token); } @Path(PATH_MODEL) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces("application/zip") @GET public Response getModel(@QueryParam("model") String model, @QueryParam("architecture") String architecture) { return restProcessTraining.getModel(model, architecture); } @Path(PATH_MODEL) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces("application/zip") @POST public Response getModel_post(@FormParam("model") String model, @FormParam("architecture") String architecture) { return restProcessTraining.getModel(model, architecture); } }
36,549
43.249395
153
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/GrobidServicePropConfiguration.java
package org.grobid.service; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; public class GrobidServicePropConfiguration { @NotEmpty @JsonProperty private String grobidHome; @NotEmpty @JsonProperty private String grobidServiceProperties; @JsonProperty private String grobidProperties; @JsonProperty private boolean modelPreload = false; @JsonProperty private String corsAllowedOrigins = "*"; @JsonProperty private String corsAllowedMethods = "OPTIONS,GET,PUT,POST,DELETE,HEAD"; @JsonProperty private String corsAllowedHeaders = "X-Requested-With,Content-Type,Accept,Origin"; public String getGrobidHome() { return grobidHome; } public void setGrobidHome(String grobidHome) { this.grobidHome = grobidHome; } public String getGrobidServiceProperties() { return grobidServiceProperties; } public void setGrobidServiceProperties(String grobidServiceProperties) { this.grobidServiceProperties = grobidServiceProperties; } public String getGrobidProperties() { return grobidProperties; } public void setGrobidProperties(String grobidProperties) { this.grobidProperties = grobidProperties; } public boolean getModelPreload() { return modelPreload; } public void setModelPreload(boolean modelPreload) { this.modelPreload = modelPreload; } public String getCorsAllowedOrigins() { return corsAllowedOrigins; } public void setCorsAllowedOrigins(String corsAllowedOrigins) { this.corsAllowedOrigins = corsAllowedOrigins; } public String getCorsAllowedMethods() { return corsAllowedMethods; } public void setCorsAllowedMethods(String corsAllowedMethods) { this.corsAllowedMethods = corsAllowedMethods; } public String getCorsAllowedHeaders() { return corsAllowedHeaders; } public void setCorsAllowedHeaders(String corsAllowedHeaders) { this.corsAllowedHeaders = corsAllowedHeaders; } }
2,139
24.47619
86
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/GrobidServiceConfiguration.java
package org.grobid.service; import com.google.inject.Singleton; import io.dropwizard.Configuration; @Singleton public class GrobidServiceConfiguration extends Configuration { private GrobidServicePropConfiguration grobid; public GrobidServicePropConfiguration getGrobid() { return grobid; } public void setGrobid(GrobidServicePropConfiguration grobid) { this.grobid = grobid; } }
422
20.15
66
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/modules/GrobidServiceModule.java
package org.grobid.service.modules; import com.codahale.metrics.MetricRegistry; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.inject.Binder; import com.google.inject.Provides; import com.hubspot.dropwizard.guicier.DropwizardAwareModule; import org.grobid.service.GrobidRestService; import org.grobid.service.GrobidServiceConfiguration; import org.grobid.service.exceptions.mapper.GrobidExceptionMapper; import org.grobid.service.exceptions.mapper.GrobidExceptionsTranslationUtility; import org.grobid.service.exceptions.mapper.GrobidServiceExceptionMapper; import org.grobid.service.exceptions.mapper.WebApplicationExceptionMapper; import org.grobid.service.process.GrobidRestProcessFiles; import org.grobid.service.process.GrobidRestProcessGeneric; import org.grobid.service.process.GrobidRestProcessString; import org.grobid.service.process.GrobidRestProcessTraining; import org.grobid.service.resources.HealthResource; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; public class GrobidServiceModule extends DropwizardAwareModule<GrobidServiceConfiguration> { @Override public void configure(Binder binder) { binder.bind(HealthResource.class); //REST binder.bind(GrobidRestService.class); binder.bind(GrobidRestProcessFiles.class); binder.bind(GrobidRestProcessGeneric.class); binder.bind(GrobidRestProcessString.class); binder.bind(GrobidRestProcessTraining.class); //Exception Mappers binder.bind(GrobidServiceExceptionMapper.class); binder.bind(GrobidExceptionsTranslationUtility.class); binder.bind(GrobidExceptionMapper.class); binder.bind(WebApplicationExceptionMapper.class); } @Provides protected ObjectMapper getObjectMapper() { return getEnvironment().getObjectMapper(); } @Provides protected MetricRegistry provideMetricRegistry() { return getMetricRegistry(); } //for unit tests protected MetricRegistry getMetricRegistry() { return getEnvironment().metrics(); } @Provides Client provideClient() { return ClientBuilder.newClient(); } }
2,202
32.892308
92
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/process/GrobidRestProcessTraining.java
package org.grobid.service.process; import com.google.inject.Inject; import com.google.inject.Singleton; import org.grobid.core.utilities.GrobidProperties; import org.grobid.core.utilities.KeyGen; import org.grobid.core.GrobidModels; import org.grobid.core.GrobidModel; import org.grobid.service.exceptions.GrobidServiceException; import org.grobid.service.util.GrobidRestUtils; //import org.grobid.core.engines.AbstractParser.Collection; import org.grobid.trainer.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.StreamingOutput; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import java.util.NoSuchElementException; import java.util.List; import java.io.*; import java.nio.charset.Charset; import java.util.concurrent.*; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.FileUtils; @Singleton public class GrobidRestProcessTraining { private static final Logger LOGGER = LoggerFactory.getLogger(GrobidRestProcessTraining.class); @Inject public GrobidRestProcessTraining() { } /** * Cehck if a model name matches an existing GROBID model, as declared in the GrobidModels registry. */ public static boolean containsModel(String targetModel) { for (GrobidModels model : GrobidModels.values()) { if (model.name().toLowerCase().equals(targetModel)) { return true; } } return false; } /** * Return a model given a model name and a target architecture (CRF default, BiLSTM-CRF or BiLSMT-CRF-ELMo). * The model is returned in a zip archive (the model being several files in the case of deep learning * models) * * @return a response object containing the zipped model */ public Response getModel(String model, String architecture) { LOGGER.debug(">> " + GrobidRestProcessGeneric.class.getName() + ".getModel"); Response response = null; String assetPath = null; try { // is the model name valid? /*if (!containsModel(model)) { throw new GrobidServiceException( "The indicated model name " + model + " is invalid or unsupported.", Status.BAD_REQUEST); }*/ GrobidModel theModel = GrobidModels.modelFor(model.toLowerCase().replace("-", "/")); File theModelFile = null; if (theModel != null) { theModelFile = new File(theModel.getModelPath()); } if (architecture == null || architecture.length() == 0) { // conservative defaulting of the architecture architecture = "crf"; } if (theModel == null) { throw new GrobidServiceException( "The indicated model name " + model + " is invalid or unsupported.", Status.BAD_REQUEST); } else if (theModelFile == null || !theModelFile.exists()) { // model name was valid but no trained model available //response = Response.status(Status.NO_CONTENT).build(); throw new GrobidServiceException( "The indicated model name " + model + " is valid but not trained.", Status.BAD_REQUEST); } else { ByteArrayOutputStream ouputStream = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(ouputStream); if (architecture.toLowerCase().equals("crf")) { response = Response.status(Status.OK).type("application/zip").build(); out.putNextEntry(new ZipEntry("model.wapiti")); byte[] buffer = new byte[1024]; try { FileInputStream in = new FileInputStream(theModelFile); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); out.closeEntry(); } catch (IOException e) { throw new GrobidServiceException("IO Exception when zipping model file", e, Status.INTERNAL_SERVER_ERROR); } } else { System.out.println(theModelFile.getAbsolutePath()); // put now the different assets in the case of a Deep Learning model, // i.e. config.json, model_weights.hdf5, preprocessor.pkl File[] files = theModelFile.listFiles(); if (files != null) { byte[] buffer = new byte[1024]; for (final File currFile : files) { if (currFile.getName().toLowerCase().endsWith(".hdf5") || currFile.getName().toLowerCase().endsWith(".json") || currFile.getName().toLowerCase().endsWith(".pkl") || currFile.getName().toLowerCase().endsWith(".txt")) { try { ZipEntry ze = new ZipEntry(currFile.getName()); out.putNextEntry(ze); FileInputStream in = new FileInputStream(currFile); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); out.closeEntry(); } catch (IOException e) { throw new GrobidServiceException("IO Exception when zipping", e, Status.INTERNAL_SERVER_ERROR); } } } } } out.finish(); response = Response .ok() .type("application/zip") .entity(ouputStream.toByteArray()) .header("Content-Disposition", "attachment; filename=\"model.zip\"") .build(); out.close(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch(GrobidServiceException exp) { LOGGER.error("Service cannot be realized: " + exp.getMessage()); response = Response.status(exp.getResponseCode()).entity(exp.getMessage()).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { } return response; } /** * Start the training of a model based on its name and a target architecture (CRF default, BiLSTM-CRF or * BiLSMT-CRF-ELMo) and a training mode. Send back a token to the calling client to retrieve training * state and eventually the evaluation metrics via the service /api/resultTraining * * @return a response object containing the token corresponding to the launched training */ public Response trainModel(String model, String architecture, String type, double ratio, int n, boolean incremental) { Response response = null; try { // is the model name valid? /*if (!containsModel(model)) { throw new GrobidServiceException( "The indicated model name " + model + " is invalid or unsupported.", Status.BAD_REQUEST); }*/ // create a token for the training String token = KeyGen.getKey(); GrobidProperties.getInstance(); File home = GrobidProperties.getInstance().getGrobidHomePath(); AbstractTrainer trainer = getTrainer(model); String tokenPath = home.getAbsolutePath() + "/training-history/" + token; File tokenDir = new File(tokenPath); if (!tokenDir.exists()) { tokenDir.mkdirs(); } ExecutorService executorService = Executors.newFixedThreadPool(1); TrainTask trainTask = new TrainTask(trainer, type, token, ratio, n, incremental); FileUtils.writeStringToFile(new File(tokenPath + "/status"), "ongoing", "UTF-8"); executorService.submit(trainTask); if (GrobidRestUtils.isResultNullOrEmpty(token)) { // it should never be the case, but let's be conservative! response = Response.status(Response.Status.NO_CONTENT).build(); } else { response = Response.status(Response.Status.OK) .entity("{\"token\": \""+ token + "\"}") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8") .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch(GrobidServiceException exp) { LOGGER.error("Service cannot be realized: " + exp.getMessage()); response = Response.status(exp.getResponseCode()).entity(exp.getMessage()).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { } return response; } /** * Note: the following should be common with TrainerRunner in grobid-trainer */ private static AbstractTrainer getTrainer(String model) { AbstractTrainer trainer; if (model.equals("affiliation") || model.equals("affiliation-address")) { trainer = new AffiliationAddressTrainer(); } else if (model.equals("date")) { trainer = new DateTrainer(); } else if (model.equals("citation")) { trainer = new CitationTrainer(); } else if (model.equals("monograph")) { trainer = new MonographTrainer(); } else if (model.equals("fulltext")) { trainer = new FulltextTrainer(); } else if (model.equals("header")) { trainer = new HeaderTrainer(); } /*else if (model.equals("header-sdo-3gpp")) { trainer = new HeaderTrainer(Collection._3GPP); } else if (model.equals("header-sdo-ietf")) { trainer = new HeaderTrainer(Collection.IETF); }*/ else if (model.equals("name-citation")) { trainer = new NameCitationTrainer(); } else if (model.equals("name-header")) { trainer = new NameHeaderTrainer(); } else if (model.equals("patent")) { trainer = new PatentParserTrainer(); } else if (model.equals("segmentation")) { trainer = new SegmentationTrainer(); } /*else if (model.equals("segmentation-sdo-3gpp")) { trainer = new SegmentationTrainer(Collection._3GPP); } else if (model.equals("segmentation-sdo-ietf")) { trainer = new SegmentationTrainer(Collection.IETF); }*/ else if (model.equals("reference-segmenter")) { trainer = new ReferenceSegmenterTrainer(); } else if (model.equals("figure")) { trainer = new FigureTrainer(); } else if (model.equals("table")) { trainer = new TableTrainer(); } else { throw new IllegalStateException("The model " + model + " is unknown."); } return trainer; } private static class TrainTask implements Runnable { private AbstractTrainer trainer; private String type; private String token; private int n = 10; private double ratio = 1.0; private boolean incremental = false; public TrainTask(AbstractTrainer trainer, String type, String token, double ratio, int n, boolean incremental) { this.trainer = trainer; this.type = type; this.token = token; this.ratio = ratio; this.n = n; this.incremental = incremental; } @Override public void run() { try { File home = GrobidProperties.getInstance().getGrobidHomePath(); String tokenPath = home.getAbsolutePath() + "/training-history/" + this.token; File tokenDir = new File(tokenPath); String results = null; //PrintStream writeAdvancement = new PrintStream(new FileOutputStream(tokenPath + "/train.txt")); //java.lang.System.setErr(writeAdvancement); switch (this.type.toLowerCase()) { // possible values are `full`, `holdout`, `split`, `nfold` case "full": AbstractTrainer.runTraining(this.trainer, this.incremental); break; case "holdout": AbstractTrainer.runTraining(this.trainer, this.incremental); results = AbstractTrainer.runEvaluation(this.trainer); break; case "split": results = AbstractTrainer.runSplitTrainingEvaluation(this.trainer, this.ratio, this.incremental); break; case "nfold": if (n == 0) { throw new IllegalArgumentException("N should be > 0"); } results = AbstractTrainer.runNFoldEvaluation(this.trainer, this.n); break; default: throw new IllegalStateException("Invalid training type: " + this.type); } //java.lang.System.setErr(java.lang.System.err); // update status FileUtils.writeStringToFile(new File(tokenPath + "/status"), "done", "UTF-8"); // write results, if any if (results != null) { FileUtils.writeStringToFile(new File(tokenPath + "/report.txt"), results, "UTF-8"); } } catch(IOException e) { LOGGER.error("Failed to write training results for token " + token, e); } } } /** * Given a training token delivered by the service `modelTraining`, this service gives the possibility * of following the advancement of the training and eventually get back the associated evaluation. * Depending on the state of the training, the service will returns: * - if the training is ongoing, an indication of advancement as a string * - it the training is completed, evaluation statistics dependeing on the selected type of training * * @return a response object containing information on the training corresponding to the token */ public Response resultTraining(String token) { Response response = null; try { // access report file under token subdirectory File home = GrobidProperties.getInstance().getGrobidHomePath(); String tokenPath = home.getAbsolutePath() + "/training-history/" + token; File tokenDirectory = new File(tokenPath); if (!tokenDirectory.exists() || !tokenDirectory.isDirectory()) { throw new GrobidServiceException( "The indicated token " + token + " is not matching an existing training.", Status.BAD_REQUEST); } // try to get the status File status = new File(tokenDirectory.getAbsolutePath() + "/status"); String statusString = null; if (!status.exists()) { LOGGER.warn("Status file is missing in the training history corresponding to token " + token); } else { statusString = FileUtils.readFileToString(status, "UTF-8"); } if (statusString != null && statusString.equals("ongoing")) { response = Response.status(Response.Status.OK) .entity("{\"status\": \"" + statusString + "\"}") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8") .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT") .build(); } else { // try to get the evaluation report File report = new File(tokenDirectory.getAbsolutePath() + "/report.txt"); if (!report.exists()) { throw new GrobidServiceException( "The indicated token " + token + " is not matching an existing ongoing or completed training.", Status.BAD_REQUEST); } else { String reportStr = FileUtils.readFileToString(report, "UTF-8"); response = Response.status(Response.Status.OK) .entity("{\"status\": \"" + statusString + "\", \"report\": " + new ObjectMapper().writeValueAsString(reportStr) + "}") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8") .header("Access-Control-Allow-Origin", "*") .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT") .build(); } } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch(GrobidServiceException exp) { LOGGER.error("Service cannot be realized: " + exp.getMessage()); response = Response.status(exp.getResponseCode()).entity(exp.getMessage()).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { } return response; } }
19,488
45.292162
143
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/process/GrobidRestProcessGeneric.java
package org.grobid.service.process; import com.google.inject.Inject; import com.google.inject.Singleton; import org.grobid.core.utilities.GrobidProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; @Singleton public class GrobidRestProcessGeneric { private static final Logger LOGGER = LoggerFactory.getLogger(GrobidRestProcessGeneric.class); @Inject public GrobidRestProcessGeneric() { } /** * Returns a string containing true, if the service is alive. * * @return a response object containing the string true if service * is alive. */ public String isAlive() { LOGGER.debug("called isAlive()..."); String retVal = null; try { retVal = Boolean.valueOf(true).toString(); } catch (Exception e) { LOGGER.error("GROBID Service is not alive, because of: ", e); retVal = Boolean.valueOf(false).toString(); } return retVal; } /** * Returns the description of how to use the grobid-service in a human * readable way (html). * * @return a response object containing a html description */ public Response getDescription_html(UriInfo uriInfo) { Response response = null; LOGGER.debug("called getDescription_html()..."); String htmlCode = "<h4>grobid-service documentation</h4>" + "This service provides a RESTful interface for using the grobid system. grobid extracts data from pdf files. For more information see: " + "<a href=\"http://grobid.readthedocs.org/\">http://grobid.readthedocs.org/</a>"; response = Response.status(Status.OK).entity(htmlCode) .type(MediaType.TEXT_HTML).build(); return response; } /** * Returns a string containing GROBID version. * * @return a response object containing version as string. */ public Response getVersion() { return Response.status(Status.OK).entity(GrobidProperties.getVersion()).build(); } }
2,203
29.191781
154
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/process/GrobidRestProcessFiles.java
package org.grobid.service.process; import com.google.inject.Inject; import com.google.inject.Singleton; import org.apache.pdfbox.pdmodel.PDDocument; import org.grobid.core.data.BibDataSet; import org.grobid.core.data.BiblioItem; import org.grobid.core.data.PatentItem; import org.grobid.core.document.Document; import org.grobid.core.document.DocumentSource; import org.grobid.core.engines.Engine; import org.grobid.core.engines.config.GrobidAnalysisConfig; import org.grobid.core.factory.GrobidPoolingFactory; import org.grobid.core.utilities.GrobidProperties; import org.grobid.core.utilities.IOUtilities; import org.grobid.core.utilities.KeyGen; import org.grobid.core.visualization.BlockVisualizer; import org.grobid.core.visualization.CitationsVisualizer; import org.grobid.core.visualization.FigureTableVisualizer; import org.grobid.service.exceptions.GrobidServiceException; import org.grobid.service.util.BibTexMediaType; import org.grobid.service.util.ExpectedResponseType; import org.grobid.service.util.GrobidRestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import javax.xml.bind.DatatypeConverter; /** * Web services consuming a file */ @Singleton public class GrobidRestProcessFiles { private static final Logger LOGGER = LoggerFactory.getLogger(GrobidRestProcessFiles.class); @Inject public GrobidRestProcessFiles() { } /** * Uploads the origin document which shall be extracted into TEI and * extracts only the header data. * * @param inputStream the data of origin document * @param consolidate consolidation parameter for the header extraction * @return a response object which contains a TEI representation of the header part */ public Response processStatelessHeaderDocument( final InputStream inputStream, final int consolidate, final boolean includeRawAffiliations, ExpectedResponseType expectedResponseType ) { LOGGER.debug(methodLogIn()); String retVal = null; Response response = null; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(inputStream, md); originFile = IOUtilities.writeInputFile(dis); byte[] digest = md.digest(); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written. ", Status.INTERNAL_SERVER_ERROR); } String md5Str = DatatypeConverter.printHexBinary(digest).toUpperCase(); BiblioItem result = new BiblioItem(); // starts conversion process retVal = engine.processHeader( originFile.getAbsolutePath(), md5Str, consolidate, includeRawAffiliations, result ); if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Response.Status.NO_CONTENT).build(); } else if (expectedResponseType == ExpectedResponseType.BIBTEX) { response = Response.status(Response.Status.OK) .entity(result.toBibTeX("-1")) .header(HttpHeaders.CONTENT_TYPE, BibTexMediaType.MEDIA_TYPE + "; charset=UTF-8") .build(); } else { response = Response.status(Response.Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Uploads the origin document which shall be extracted into TEI. * * @param inputStream the data of origin document * @param consolidateHeader the consolidation option allows GROBID to exploit Crossref * for improving header information * @param consolidateCitations the consolidation option allows GROBID to exploit Crossref * for improving citations information * @param startPage give the starting page to consider in case of segmentation of the * PDF, -1 for the first page (default) * @param endPage give the end page to consider in case of segmentation of the * PDF, -1 for the last page (default) * @param generateIDs if true, generate random attribute id on the textual elements of * the resulting TEI * @param segmentSentences if true, return results with segmented sentences * @return a response object mainly contain the TEI representation of the * full text */ public Response processFulltextDocument(final InputStream inputStream, final int consolidateHeader, final int consolidateCitations, final boolean includeRawAffiliations, final boolean includeRawCitations, final int startPage, final int endPage, final boolean generateIDs, final boolean segmentSentences, final List<String> teiCoordinates) throws Exception { LOGGER.debug(methodLogIn()); String retVal = null; Response response = null; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(inputStream, md); originFile = IOUtilities.writeInputFile(dis); byte[] digest = md.digest(); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } String md5Str = DatatypeConverter.printHexBinary(digest).toUpperCase(); // starts conversion process GrobidAnalysisConfig config = GrobidAnalysisConfig.builder() .consolidateHeader(consolidateHeader) .consolidateCitations(consolidateCitations) .includeRawAffiliations(includeRawAffiliations) .includeRawCitations(includeRawCitations) .startPage(startPage) .endPage(endPage) .generateTeiIds(generateIDs) .generateTeiCoordinates(teiCoordinates) .withSentenceSegmentation(segmentSentences) .build(); retVal = engine.fullTextToTEI(originFile, md5Str, config); if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Response.Status.NO_CONTENT).build(); } else { response = Response.status(Response.Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } if (originFile != null) IOUtilities.removeTempFile(originFile); } LOGGER.debug(methodLogOut()); return response; } /** * Uploads the origin document which shall be extracted into TEI + assets in a ZIP * archive. * * @param inputStream the data of origin document * @param consolidateHeader the consolidation option allows GROBID to exploit Crossref * for improving header information * @param consolidateCitations the consolidation option allows GROBID to exploit Crossref * for improving citations information * @param startPage give the starting page to consider in case of segmentation of the * PDF, -1 for the first page (default) * @param endPage give the end page to consider in case of segmentation of the * PDF, -1 for the last page (default) * @param generateIDs if true, generate random attribute id on the textual elements of * the resulting TEI * @param segmentSentences if true, return results with segmented sentences * @return a response object mainly contain the TEI representation of the * full text */ public Response processStatelessFulltextAssetDocument(final InputStream inputStream, final int consolidateHeader, final int consolidateCitations, final boolean includeRawAffiliations, final boolean includeRawCitations, final int startPage, final int endPage, final boolean generateIDs, final boolean segmentSentences, final List<String> teiCoordinates) throws Exception { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; File originFile = null; Engine engine = null; String assetPath = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(inputStream, md); originFile = IOUtilities.writeInputFile(dis); byte[] digest = md.digest(); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } // set the path for the asset files assetPath = GrobidProperties.getTempPath().getPath() + File.separator + KeyGen.getKey(); String md5Str = DatatypeConverter.printHexBinary(digest).toUpperCase(); // starts conversion process GrobidAnalysisConfig config = GrobidAnalysisConfig.builder() .consolidateHeader(consolidateHeader) .consolidateCitations(consolidateCitations) .includeRawAffiliations(includeRawAffiliations) .includeRawCitations(includeRawCitations) .startPage(startPage) .endPage(endPage) .generateTeiIds(generateIDs) .generateTeiCoordinates(teiCoordinates) .pdfAssetPath(new File(assetPath)) .withSentenceSegmentation(segmentSentences) .build(); retVal = engine.fullTextToTEI(originFile, md5Str, config); if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK).type("application/zip").build(); ByteArrayOutputStream ouputStream = new ByteArrayOutputStream(); ZipOutputStream out = new ZipOutputStream(ouputStream); out.putNextEntry(new ZipEntry("tei.xml")); out.write(retVal.getBytes(Charset.forName("UTF-8"))); // put now the assets, i.e. all the files under the asset path File assetPathDir = new File(assetPath); if (assetPathDir.exists()) { File[] files = assetPathDir.listFiles(); if (files != null) { byte[] buffer = new byte[1024]; for (final File currFile : files) { if (currFile.getName().toLowerCase().endsWith(".jpg") || currFile.getName().toLowerCase().endsWith(".png")) { try { ZipEntry ze = new ZipEntry(currFile.getName()); out.putNextEntry(ze); FileInputStream in = new FileInputStream(currFile); int len; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } in.close(); out.closeEntry(); } catch (IOException e) { throw new GrobidServiceException("IO Exception when zipping", e, Status.INTERNAL_SERVER_ERROR); } } } } } out.finish(); response = Response .ok() .type("application/zip") .entity(ouputStream.toByteArray()) .header("Content-Disposition", "attachment; filename=\"result.zip\"") .build(); out.close(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); if (assetPath != null) { IOUtilities.removeTempDirectory(assetPath); } if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Process a patent document in PDF for extracting and parsing citations in the description body. * * @param inputStream the data of origin document * @return a response object mainly containing the TEI representation of the * citation */ public Response processCitationPatentPDF(final InputStream inputStream, final int consolidate, final boolean includeRawCitations) throws Exception { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } originFile = IOUtilities.writeInputFile(inputStream); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } // starts conversion process List<PatentItem> patents = new ArrayList<>(); List<BibDataSet> articles = new ArrayList<>(); retVal = engine.processAllCitationsInPDFPatent(originFile.getAbsolutePath(), articles, patents, consolidate, includeRawCitations); if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Process a patent document encoded in ST.36 for extracting and parsing citations in the description body. * * @param inputStream the data of origin document * @return a response object mainly containing the TEI representation of the * citation */ public Response processCitationPatentST36(final InputStream inputStream, final int consolidate, final boolean includeRawCitations) throws Exception { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } originFile = IOUtilities.writeInputFile(inputStream); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } // starts conversion process List<PatentItem> patents = new ArrayList<>(); List<BibDataSet> articles = new ArrayList<>(); retVal = engine.processAllCitationsInXMLPatent(originFile.getAbsolutePath(), articles, patents, consolidate, includeRawCitations); if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { //response = Response.status(Status.OK).entity(retVal).type(MediaType.APPLICATION_XML).build(); response = Response.status(Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Uploads the origin document, extract and parser all its references. * * @param inputStream the data of origin document * @param consolidate if the result has to be consolidated with CrossRef access. * @param includeRawCitations determines whether the original citation (called "raw") should be included in the * output * @param expectedResponseType determines whether XML or BibTeX should be returned * @return a response object mainly contain the TEI representation of the full text */ public Response processStatelessReferencesDocument(final InputStream inputStream, final int consolidate, final boolean includeRawCitations, ExpectedResponseType expectedResponseType) { LOGGER.debug(methodLogIn()); Response response; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(inputStream, md); originFile = IOUtilities.writeInputFile(dis); byte[] digest = md.digest(); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } String md5Str = DatatypeConverter.printHexBinary(digest).toUpperCase(); // starts conversion process List<BibDataSet> bibDataSetList = engine.processReferences(originFile, md5Str, consolidate); if (bibDataSetList.isEmpty()) { response = Response.status(Status.NO_CONTENT).build(); } else if (expectedResponseType == ExpectedResponseType.BIBTEX) { StringBuilder result = new StringBuilder(); GrobidAnalysisConfig config = new GrobidAnalysisConfig.GrobidAnalysisConfigBuilder().includeRawCitations(includeRawCitations).build(); int p = 0; for (BibDataSet res : bibDataSetList) { result.append(res.getResBib().toBibTeX(Integer.toString(p), config)); result.append("\n"); p++; } response = Response.status(Status.OK) .entity(result.toString()) .header(HttpHeaders.CONTENT_TYPE, BibTexMediaType.MEDIA_TYPE + "; charset=UTF-8") .build(); } else { StringBuilder result = new StringBuilder(); // dummy header result.append("<TEI xmlns=\"http://www.tei-c.org/ns/1.0\" " + "xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "\n xmlns:mml=\"http://www.w3.org/1998/Math/MathML\">\n"); result.append("\t<teiHeader/>\n\t<text>\n\t\t<front/>\n\t\t" + "<body/>\n\t\t<back>\n\t\t\t<div>\n\t\t\t\t<listBibl>\n"); int p = 0; for (BibDataSet bibDataSet : bibDataSetList) { result.append(bibDataSet.toTEI(p, includeRawCitations)); result.append("\n"); p++; } result.append("\t\t\t\t</listBibl>\n\t\t\t</div>\n\t\t</back>\n\t</text>\n</TEI>\n"); response = Response.status(Status.OK) .entity(result.toString()) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Uploads the origin PDF, process it and return the PDF augmented with annotations. * * @param inputStream the data of origin PDF * @param fileName the name of origin PDF * @param type gives type of annotation * @return a response object containing the annotated PDF */ public Response processPDFAnnotation(final InputStream inputStream, final String fileName, final int consolidateHeader, final int consolidateCitations, final boolean includeRawAffiliations, final boolean includeRawCitations, final GrobidRestUtils.Annotation type) throws Exception { LOGGER.debug(methodLogIn()); Response response = null; PDDocument out = null; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } originFile = IOUtilities.writeInputFile(inputStream); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } out = annotate( originFile, type, engine, consolidateHeader, consolidateCitations, includeRawAffiliations, includeRawCitations ); if (out != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); out.save(outputStream); response = Response .ok() .type("application/pdf") .entity(outputStream.toByteArray()) .header("Content-Disposition", "attachment; filename=\"" + fileName + "\"") .build(); } else { response = Response.status(Status.NO_CONTENT).build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); try { out.close(); } catch (IOException e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); } if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Uploads the origin PDF, process it and return PDF annotations for references in JSON. * * @param inputStream the data of origin PDF * @return a response object containing the JSON annotations */ public Response processPDFReferenceAnnotation(final InputStream inputStream, final int consolidateHeader, final int consolidateCitations, final boolean includeRawCitations, final boolean includeFiguresTables) throws Exception { LOGGER.debug(methodLogIn()); Response response = null; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } MessageDigest md = MessageDigest.getInstance("MD5"); DigestInputStream dis = new DigestInputStream(inputStream, md); originFile = IOUtilities.writeInputFile(dis); byte[] digest = md.digest(); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } String md5Str = DatatypeConverter.printHexBinary(digest).toUpperCase(); List<String> elementWithCoords = new ArrayList<>(); elementWithCoords.add("ref"); elementWithCoords.add("biblStruct"); GrobidAnalysisConfig config = new GrobidAnalysisConfig .GrobidAnalysisConfigBuilder() .generateTeiCoordinates(elementWithCoords) .consolidateHeader(consolidateHeader) .consolidateCitations(consolidateCitations) .includeRawCitations(includeRawCitations) .build(); Document teiDoc = engine.fullTextToTEIDoc(originFile, config); String json = CitationsVisualizer.getJsonAnnotations(teiDoc, null, includeFiguresTables); if (json != null) { response = Response .ok() .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8") .entity(json) .build(); } else { response = Response.status(Status.NO_CONTENT).build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Annotate the citations in a PDF patent document with JSON annotations. * * @param inputStream the data of origin document * @return a response object mainly containing the TEI representation of the * citation */ public Response annotateCitationPatentPDF(final InputStream inputStream, final int consolidate, final boolean includeRawCitations) throws Exception { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; File originFile = null; Engine engine = null; try { engine = Engine.getEngine(true); // conservative check, if no engine is free in the pool a NoSuchElementException is normally thrown if (engine == null) { throw new GrobidServiceException( "No GROBID engine available", Status.SERVICE_UNAVAILABLE); } originFile = IOUtilities.writeInputFile(inputStream); if (originFile == null) { LOGGER.error("The input file cannot be written."); throw new GrobidServiceException( "The input file cannot be written.", Status.INTERNAL_SERVER_ERROR); } // starts conversion process retVal = engine.annotateAllCitationsInPDFPatent(originFile.getAbsolutePath(), consolidate, includeRawCitations); if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception exp) { LOGGER.error("An unexpected exception occurs. ", exp); response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(exp.getMessage()).build(); } finally { if (originFile != null) IOUtilities.removeTempFile(originFile); if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } public String methodLogIn() { return ">> " + GrobidRestProcessFiles.class.getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(); } public String methodLogOut() { return "<< " + GrobidRestProcessFiles.class.getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(); } protected PDDocument annotate(File originFile, final GrobidRestUtils.Annotation type, Engine engine, final int consolidateHeader, final int consolidateCitations, final boolean includeRawAffiliations, final boolean includeRawCitations) throws Exception { // starts conversion process PDDocument outputDocument = null; // list of TEI elements that should come with coordinates List<String> elementWithCoords = new ArrayList<>(); if (type == GrobidRestUtils.Annotation.CITATION) { elementWithCoords.add("ref"); elementWithCoords.add("biblStruct"); } else if (type == GrobidRestUtils.Annotation.FIGURE) { elementWithCoords.add("figure"); } GrobidAnalysisConfig config = new GrobidAnalysisConfig .GrobidAnalysisConfigBuilder() .consolidateHeader(consolidateHeader) .consolidateCitations(consolidateCitations) .includeRawAffiliations(includeRawAffiliations) .includeRawCitations(includeRawCitations) .generateTeiCoordinates(elementWithCoords) .build(); DocumentSource documentSource = DocumentSource.fromPdf(originFile, config.getStartPage(), config.getEndPage(), true, true, false); Document teiDoc = engine.fullTextToTEIDoc(documentSource, config); documentSource = DocumentSource.fromPdf(originFile, config.getStartPage(), config.getEndPage(), true, true, false); PDDocument document = PDDocument.load(originFile); //If no pages, skip the document if (document.getNumberOfPages() > 0) { outputDocument = dispatchProcessing(type, document, documentSource, teiDoc); } else { throw new RuntimeException("Cannot identify any pages in the input document. " + "The document cannot be annotated. Please check whether the document is valid or the logs."); } documentSource.close(true, true, false); return outputDocument; } protected PDDocument dispatchProcessing(GrobidRestUtils.Annotation type, PDDocument document, DocumentSource documentSource, Document teiDoc ) throws Exception { PDDocument out = null; if (type == GrobidRestUtils.Annotation.CITATION) { out = CitationsVisualizer.annotatePdfWithCitations(document, teiDoc, null); } else if (type == GrobidRestUtils.Annotation.BLOCK) { out = BlockVisualizer.annotateBlocks(document, documentSource.getXmlFile(), teiDoc, true, true, false); } else if (type == GrobidRestUtils.Annotation.FIGURE) { out = FigureTableVisualizer.annotateFigureAndTables(document, documentSource.getXmlFile(), teiDoc, true, true, true, false, false); } return out; } }
41,513
45.384358
150
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/process/GrobidRestProcessString.java
package org.grobid.service.process; import java.util.List; import java.util.ArrayList; import java.util.NoSuchElementException; import javax.ws.rs.core.HttpHeaders; import javax.inject.Inject; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import com.google.inject.Singleton; import org.grobid.core.data.Affiliation; import org.grobid.core.data.BiblioItem; import org.grobid.core.data.PatentItem; import org.grobid.core.data.BibDataSet; import org.grobid.core.data.Date; import org.grobid.core.data.Person; import org.grobid.core.engines.Engine; import org.grobid.core.engines.config.GrobidAnalysisConfig; import org.grobid.core.factory.GrobidPoolingFactory; import org.grobid.service.util.BibTexMediaType; import org.grobid.service.util.ExpectedResponseType; import org.grobid.service.util.GrobidRestUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Web services consuming String * */ @Singleton public class GrobidRestProcessString { private static final Logger LOGGER = LoggerFactory.getLogger(GrobidRestProcessString.class); @Inject public GrobidRestProcessString() { } /** * Parse a raw date and return the corresponding normalized date. * * @param date raw date string * @return a response object containing the structured xml representation of * the date */ public Response processDate(String date) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; Engine engine = null; try { LOGGER.debug(">> set raw date for stateless service'..."); engine = Engine.getEngine(true); date = date.replaceAll("\\n", " ").replaceAll("\\t", " "); List<Date> dates = engine.processDate(date); if (dates != null) { for(Date theDate : dates) { if (retVal == null) { retVal = ""; } retVal += theDate.toTEI(); } } if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw sequence of names from a header section and return the * corresponding normalized authors. * * @param names string of the raw sequence of header authors * @return a response object containing the structured xml representation of * the authors */ public Response processNamesHeader(String names) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; Engine engine = null; try { LOGGER.debug(">> set raw header author sequence for stateless service'..."); engine = Engine.getEngine(true); names = names.replaceAll("\\n", " ").replaceAll("\\t", " "); List<Person> authors = engine.processAuthorsHeader(names); if (authors != null) { for(Person person : authors) { if (retVal == null) { retVal = ""; } retVal += person.toTEI(false); } } if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { //response = Response.status(Status.OK).entity(retVal).type(MediaType.TEXT_PLAIN).build(); response = Response.status(Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw sequence of names from a header section and return the * corresponding normalized authors. * * @param names string of the raw sequence of header authors. * @return a response object containing the structured xml representation of * the authors */ public Response processNamesCitation(String names) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; Engine engine = null; try { LOGGER.debug(">> set raw citation author sequence for stateless service'..."); engine = Engine.getEngine(true); names = names.replaceAll("\\n", " ").replaceAll("\\t", " "); List<Person> authors = engine.processAuthorsCitation(names); if (authors != null) { for(Person person : authors) { if (retVal == null) { retVal = ""; } retVal += person.toTEI(false); } } if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { response = Response.status(Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw sequence of affiliations and return the corresponding * normalized affiliations with address. * * @param affiliation of the raw sequence of affiliation+address * @return a response object containing the structured xml representation of * the affiliation */ public Response processAffiliations(String affiliation) { LOGGER.debug(methodLogIn()); Response response = null; String retVal = null; Engine engine = null; try { LOGGER.debug(">> set raw affiliation + address blocks for stateless service'..."); engine = Engine.getEngine(true); affiliation = affiliation.replaceAll("\\t", " "); List<Affiliation> affiliationList = engine.processAffiliation(affiliation); if (affiliationList != null) { for(Affiliation affi : affiliationList) { if (retVal == null) { retVal = ""; } retVal += affi.toTEI(); } } if (GrobidRestUtils.isResultNullOrEmpty(retVal)) { response = Response.status(Status.NO_CONTENT).build(); } else { //response = Response.status(Status.OK).entity(retVal).type(MediaType.TEXT_PLAIN).build(); response = Response.status(Status.OK) .entity(retVal) .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a raw reference string and return the corresponding * structured reference affiliations in the requested format. * * @param citation * string of the raw reference * @param expectedResponseType * states which media type the caller expected (xml tei or bibtex) * @return a response object containing the structured representation of * the reference */ public Response processCitation(String citation, GrobidAnalysisConfig config, ExpectedResponseType expectedResponseType) { LOGGER.debug(methodLogIn()); Response response; Engine engine = null; try { engine = Engine.getEngine(true); //citation = citation.replaceAll("\\n", " ").replaceAll("\\t", " "); BiblioItem biblioItem = engine.processRawReference(citation, config.getConsolidateCitations()); if (biblioItem == null) { response = Response.status(Status.NO_CONTENT).build(); } else if (expectedResponseType == ExpectedResponseType.BIBTEX) { response = Response.status(Status.OK) .entity(biblioItem.toBibTeX("-1", config)) .header(HttpHeaders.CONTENT_TYPE, BibTexMediaType.MEDIA_TYPE + "; charset=UTF-8") .build(); } else { response = Response.status(Status.OK) .entity(biblioItem.toTEI(-1, config)) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a list of raw sequence of reference strings and return the corresponding * normalized bilbiographical objects in the same order and in the reuqested format * * @param citation * list of strings of the raw sequence of reference strings * @param expectedResponseType * states which media type the caller expected (xml tei or bibtex) * @return a response object containing the structured representation of * the references */ public Response processCitationList(List<String> citations, GrobidAnalysisConfig config, ExpectedResponseType expectedResponseType) { LOGGER.debug(methodLogIn()); Response response; Engine engine = null; try { engine = Engine.getEngine(true); List<BiblioItem> biblioItems = engine.processRawReferences(citations, config.getConsolidateCitations()); if (biblioItems == null || biblioItems.size() == 0) { response = Response.status(Status.NO_CONTENT).build(); } else if (expectedResponseType == ExpectedResponseType.BIBTEX) { StringBuilder responseContent = new StringBuilder(); int n = 0; for(BiblioItem biblioItem : biblioItems) { responseContent.append(biblioItem.toBibTeX(""+n, config)); responseContent.append("\n"); n++; } response = Response.status(Status.OK) .entity(responseContent.toString()) .header(HttpHeaders.CONTENT_TYPE, BibTexMediaType.MEDIA_TYPE + "; charset=UTF-8") .build(); } else { StringBuilder responseContent = new StringBuilder(); // add some TEI envelop responseContent.append("<TEI xmlns=\"http://www.tei-c.org/ns/1.0\" " + "xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + "\n xmlns:mml=\"http://www.w3.org/1998/Math/MathML\">\n"); responseContent.append("\t<teiHeader/>\n\t<text>\n\t\t<front/>\n\t\t" + "<body/>\n\t\t<back>\n\t\t\t<div>\n\t\t\t\t<listBibl>\n"); int n = 0; for(BiblioItem biblioItem : biblioItems) { responseContent.append(biblioItem.toTEI(n, config)); responseContent.append("\n"); n++; } responseContent.append("\t\t\t\t</listBibl>\n\t\t\t</div>\n\t\t</back>\n\t</text>\n</TEI>\n"); response = Response.status(Status.OK) .entity(responseContent.toString()) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } /** * Parse a patent description text and return the extracted and parsed patent and non-patent citations. * * @param text * string of the patent description text to be processed * @param consolidate * consolidation parameter for the non patent extracted and parsed citation * * @return a response object containing the structured xml representation of * the affiliation */ public Response processCitationPatentTXT(String text, int consolidate, boolean includeRawCitations) { LOGGER.debug(methodLogIn()); Response response = null; Engine engine = null; try { engine = Engine.getEngine(true); List<PatentItem> patents = new ArrayList<PatentItem>(); List<BibDataSet> articles = new ArrayList<BibDataSet>(); text = text.replaceAll("\\t", " "); String result = engine.processAllCitationsInPatent(text, articles, patents, consolidate, includeRawCitations); if (result == null) { response = Response.status(Status.NO_CONTENT).build(); } else { //response = Response.status(Status.OK).entity(result).type(MediaType.APPLICATION_XML).build(); response = Response.status(Status.OK) .entity(result) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML + "; charset=UTF-8") .build(); } } catch (NoSuchElementException nseExp) { LOGGER.error("Could not get an engine from the pool within configured time. Sending service unavailable."); response = Response.status(Status.SERVICE_UNAVAILABLE).build(); } catch (Exception e) { LOGGER.error("An unexpected exception occurs. ", e); response = Response.status(Status.INTERNAL_SERVER_ERROR).build(); } finally { if (engine != null) { GrobidPoolingFactory.returnEngine(engine); } } LOGGER.debug(methodLogOut()); return response; } public String methodLogIn() { return ">> " + GrobidRestProcessString.class.getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(); } public String methodLogOut() { return "<< " + GrobidRestProcessString.class.getName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName(); } }
15,456
35.541371
134
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/util/ExpectedResponseType.java
package org.grobid.service.util; public enum ExpectedResponseType { BIBTEX, XML }
87
13.666667
34
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/util/GrobidRestUtils.java
package org.grobid.service.util; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GrobidRestUtils { private static final Logger LOGGER = LoggerFactory .getLogger(GrobidRestUtils.class); // type of PDF annotation for visualization purposes public enum Annotation { CITATION, BLOCK, FIGURE } /** * Check whether the result is null or empty. */ public static boolean isResultNullOrEmpty(String result) { return StringUtils.isBlank(result); } public static Annotation getAnnotationFor(int type) { GrobidRestUtils.Annotation annotType = null; if (type == 0) annotType = GrobidRestUtils.Annotation.CITATION; else if (type == 1) annotType = GrobidRestUtils.Annotation.BLOCK; else if (type == 2) annotType = GrobidRestUtils.Annotation.FIGURE; return annotType; } }
981
25.540541
62
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/util/ZipUtils.java
package org.grobid.service.util; import org.grobid.core.utilities.IOUtilities; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.io.PushbackInputStream; import java.util.zip.GZIPInputStream; public class ZipUtils { public static InputStream decompressStream(InputStream input) throws Exception { PushbackInputStream pb = new PushbackInputStream( input, 2 ); //we need a pushbackstream to look ahead byte [] signature = new byte[2]; try { pb.read( signature ); //read the signature pb.unread( signature ); //push back the signature to the stream } catch(Exception e) { } if( signature[ 0 ] == (byte) 0x1f && signature[ 1 ] == (byte) 0x8b ) //check if matches standard gzip maguc number return new GZIPInputStream( pb ); else return pb; } public static final void copyInputStream(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) >= 0) out.write(buffer, 0, len); in.close(); out.close(); } public static final void main(String[] args) { Enumeration entries; ZipFile zipFile; if (args.length != 1) { System.err.println("Usage: Unzip zipfile"); return; } String pPath = args[0]; try { zipFile = new ZipFile(pPath); entries = zipFile.entries(); File tempDir = IOUtilities.newTempFile("GROBID", Long.toString(System.nanoTime())); if (!(tempDir.delete())) { throw new IOException("Could not delete temp file: " + tempDir.getAbsolutePath()); } if (!(tempDir.mkdir())) { throw new IOException("Could not create temp directory: " + tempDir.getAbsolutePath()); } while (entries.hasMoreElements()) { ZipEntry entry = (ZipEntry) entries.nextElement(); if (entry.isDirectory()) { // Assume directories are stored parents first then // children. System.err.println("Extracting directory: " + entry.getName()); // This is not robust, just for demonstration purposes. (new File(tempDir.getAbsolutePath() + File.separator + entry.getName())).mkdir(); continue; } System.err.println("Extracting file: " + entry.getName()); copyInputStream( zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(tempDir .getAbsolutePath() + File.separator + entry.getName()))); } zipFile.close(); } catch (IOException ioe) { System.err.println("Unhandled exception:"); ioe.printStackTrace(); return; } } }
2,783
25.264151
119
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/util/BibTexMediaType.java
package org.grobid.service.util; public class BibTexMediaType { public static final String MEDIA_TYPE = "application/x-bibtex"; }
135
21.666667
67
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/exceptions/GrobidServiceException.java
package org.grobid.service.exceptions; import org.grobid.core.exceptions.GrobidException; import javax.ws.rs.core.Response; public class GrobidServiceException extends GrobidException { private static final long serialVersionUID = -756089338090769910L; private Response.Status responseCode; public GrobidServiceException(Response.Status responseCode) { super(); this.responseCode = responseCode; } public GrobidServiceException(String msg, Response.Status responseCode) { super(msg); this.responseCode = responseCode; } public GrobidServiceException(String msg, Throwable cause, Response.Status responseCode) { super(msg, cause); this.responseCode = responseCode; } public Response.Status getResponseCode() { return responseCode; } }
837
26.933333
94
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/exceptions/GrobidServicePropertyException.java
package org.grobid.service.exceptions; import javax.ws.rs.core.Response; public class GrobidServicePropertyException extends GrobidServiceException { private static final long serialVersionUID = -756080338090769910L; public GrobidServicePropertyException() { super(Response.Status.INTERNAL_SERVER_ERROR); } public GrobidServicePropertyException(String msg) { super(msg, Response.Status.INTERNAL_SERVER_ERROR); } public GrobidServicePropertyException(String msg, Throwable cause) { super(msg, cause, Response.Status.INTERNAL_SERVER_ERROR); } }
601
27.666667
76
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/exceptions/mapper/GrobidStatusToHttpStatusMapper.java
package org.grobid.service.exceptions.mapper; import org.grobid.core.exceptions.GrobidExceptionStatus; import javax.ws.rs.core.Response; public class GrobidStatusToHttpStatusMapper { public static Response.Status getStatusCode(GrobidExceptionStatus status) { switch (status) { case BAD_INPUT_DATA: return Response.Status.BAD_REQUEST; case TAGGING_ERROR: return Response.Status.INTERNAL_SERVER_ERROR; case PARSING_ERROR: return Response.Status.INTERNAL_SERVER_ERROR; case TIMEOUT: return Response.Status.CONFLICT; case TOO_MANY_BLOCKS: return Response.Status.CONFLICT; case NO_BLOCKS: return Response.Status.BAD_REQUEST; case PDFALTO_CONVERSION_FAILURE: return Response.Status.INTERNAL_SERVER_ERROR; case TOO_MANY_TOKENS: return Response.Status.CONFLICT; case GENERAL: return Response.Status.INTERNAL_SERVER_ERROR; default: return Response.Status.INTERNAL_SERVER_ERROR; } } }
1,182
34.848485
79
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/exceptions/mapper/GrobidServiceExceptionMapper.java
package org.grobid.service.exceptions.mapper; import com.google.inject.Inject; import org.grobid.service.exceptions.GrobidServiceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class GrobidServiceExceptionMapper implements ExceptionMapper<GrobidServiceException> { private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionMapper.class); @Context protected HttpHeaders headers; @Context private UriInfo uriInfo; @Inject private GrobidExceptionsTranslationUtility mapper; @Inject public GrobidServiceExceptionMapper() { } @Override public Response toResponse(GrobidServiceException exception) { return mapper.processException(exception, exception.getResponseCode()); } }
998
25.289474
94
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/exceptions/mapper/GrobidExceptionMapper.java
package org.grobid.service.exceptions.mapper; import com.google.inject.Inject; import org.grobid.core.exceptions.GrobidException; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class GrobidExceptionMapper implements ExceptionMapper<GrobidException> { @Context protected HttpHeaders headers; @Context private UriInfo uriInfo; @Inject private GrobidExceptionsTranslationUtility mapper; @Inject public GrobidExceptionMapper() { } @Override public Response toResponse(GrobidException exception) { return mapper.processException(exception, GrobidStatusToHttpStatusMapper.getStatusCode(exception.getStatus())); } }
855
22.777778
119
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/exceptions/mapper/WebApplicationExceptionMapper.java
package org.grobid.service.exceptions.mapper; import com.google.inject.Inject; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class WebApplicationExceptionMapper implements ExceptionMapper<WebApplicationException> { @Inject public WebApplicationExceptionMapper() { } @Override public Response toResponse(WebApplicationException exception) { Response.Status exceptionStatus = Response.Status.fromStatusCode(exception.getResponse().getStatus()); if (exceptionStatus != null) { return Response.status(exceptionStatus).build(); } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } }
796
28.518519
110
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/exceptions/mapper/GrobidExceptionsTranslationUtility.java
package org.grobid.service.exceptions.mapper; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Joiner; import com.google.common.base.Throwables; import org.grobid.core.exceptions.GrobidExceptionStatus; import org.slf4j.MDC; import javax.inject.Inject; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Provider public class GrobidExceptionsTranslationUtility { @Inject public GrobidExceptionsTranslationUtility() { } public Response processException(Throwable exception, Response.Status status) { try { fillMdc(exception, status); List<String> descriptions = getExceptionDescriptions(exception, status); // String requestUri = uriInfo.getRequestUri().toString(); return Response.status(status) .type(MediaType.APPLICATION_JSON_TYPE) .entity(buildJson(getExceptionName(exception), descriptions, status, null, null)) .build(); } finally { cleanMdc(); } } public String getExceptionName(Throwable exception) { String exceptionName = exception.getClass().getCanonicalName(); if (exception.getCause() != null) { exceptionName = exception.getCause().getClass().getCanonicalName(); } return exceptionName; } public void fillMdc(Throwable exception, Response.Status status) { MDC.put("ExceptionName", getExceptionName(exception)); MDC.put("StatusCode", String.valueOf(status.getStatusCode())); MDC.put("ReasonPhrase", status.getReasonPhrase()); MDC.put("StatusFamily", status.getFamily().toString()); MDC.put("StackTrace", Throwables.getStackTraceAsString(exception)); } public void cleanMdc() { MDC.remove("ExceptionName"); MDC.remove("StringErrorCode"); MDC.remove("StatusCode"); MDC.remove("ReasonPhrase"); MDC.remove("StatusFamily"); MDC.remove("StackTrace"); } public List<String> getExceptionDescriptions(Throwable exception, Response.Status status) { List<String> descriptions = new ArrayList<>(); Throwable currentException = exception; int maxIterations = 0; while (currentException != null) { StringBuilder sb = new StringBuilder(50); sb.append(currentException.getClass().getName()); if (currentException.getMessage() != null) { sb.append(":").append(currentException.getMessage()); } descriptions.add(sb.toString()); currentException = currentException.getCause(); maxIterations++; if (maxIterations > 4) { break; } } return descriptions; } public String buildJson(String type, List<String> descriptions, Response.Status status, GrobidExceptionStatus grobidExceptionStatus, String requestUri) { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.createObjectNode(); root.put("type", type); root.put("description", Joiner.on("\n").join(descriptions)); root.put("code", status.getStatusCode()); root.put("requestUri", requestUri); String correlationId = MDC.get("correlationId"); if (correlationId != null) { root.put("correlationId", correlationId); } if (grobidExceptionStatus != null) { root.put("grobidExceptionStatus", grobidExceptionStatus.name()); } String json; try { json = mapper.writeValueAsString(root); } catch (IOException e) { // LOGGER.warn("Error in ServiceExceptionMapper: ", e); json = "{\"description\": \"Internal error: " + e.getMessage() + "\"}"; } return json; } }
4,054
34.26087
157
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/parser/Xml2HtmlParser.java
package org.grobid.service.parser; import org.apache.commons.lang3.StringUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class Xml2HtmlParser extends DefaultHandler { private static final String BR = "<br>"; private static final String SLASH = "/"; private static final String ROYAL_BLUE = "RoyalBlue"; private static final String ORANGE = "Orange"; private static final String EQUALS = "="; private static final String LESS_THAN = "&lt;"; private static final String GREATER_THAN = "&gt;"; private static final String SPACE = "&nbsp;"; private static final String DARK_VIOLET = "DarkViolet"; StringBuffer htmlOutput; int depth; boolean inline; /** * Constructor. */ public Xml2HtmlParser() { htmlOutput = new StringBuffer(); depth = 0; inline = false; } /** * Return the xml file formatted to be displayed as html. * * @return String. */ public String getHTML() { return htmlOutput.toString(); } /** * {@inheritDoc} */ @Override public void characters(char[] buffer, int start, int length) throws SAXException { final String value = new String(buffer, start, length); if (StringUtils.isBlank(value)) { } else if (value.length() <= 40 && StringUtils.isNotBlank(value)) { htmlOutput.append(value); inline = true; } else { htmlOutput.append(BR); String[] words = value.split("\\p{Space}"); int cpt = 0; for (String currWord : words) { if (cpt == 0) { indent(); space(3); } cpt += currWord.length() + 1; if (cpt < 100) { htmlOutput.append(currWord); htmlOutput.append(SPACE); } else { cpt = 0; htmlOutput.append(currWord); if (!currWord.equals(words[words.length - 1])) { htmlOutput.append(BR); } } } inline = false; } } /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { depth++; addTag(qName, attributes); } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { endTag(qName); depth--; } protected void addTag(String qName, Attributes attributes) { htmlOutput.append(BR); indent(); // Tag name htmlOutput.append("<font color=" + DARK_VIOLET + ">").append(LESS_THAN); htmlOutput.append(qName).append("</font>"); // Attributes String name; String value; for (int i = 0; i < attributes.getLength(); i++) { name = attributes.getQName(i); value = attributes.getValue(i); htmlOutput.append(SPACE); htmlOutput.append("<font color=" + ORANGE + ">"); htmlOutput.append(name).append(EQUALS).append("</font>"); htmlOutput.append("<font color=" + ROYAL_BLUE + ">\"") .append(value); htmlOutput.append("\"</font>"); } // End of tag htmlOutput.append("<font color=" + DARK_VIOLET + ">").append( GREATER_THAN); htmlOutput.append("</font>"); } protected void endTag(String qName) { if (inline) { inline = false; } else { htmlOutput.append(BR); indent(); } htmlOutput.append("<font color=" + DARK_VIOLET + ">").append( LESS_THAN + SLASH); htmlOutput.append(qName).append(GREATER_THAN); htmlOutput.append("</font>"); } /** * Add indentation to xml. */ private void indent() { for (int i = 0; i < depth * 3; i++) { htmlOutput.append(SPACE); } } /** * Add space to xml. * * @param sapce * number of spaces. */ private void space(int nbSpace) { for (int i = 0; i < nbSpace; i++) { htmlOutput.append(SPACE); } } }
3,664
21.212121
74
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/parser/ChangePropertyParser.java
package org.grobid.service.parser; import org.grobid.core.exceptions.GrobidPropertyException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; public class ChangePropertyParser { Document doc; /** * Constructor of ChangePropertyParser. * * @param pInput the xml to parse. * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public ChangePropertyParser(String pInput) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(new InputSource(new StringReader(pInput))); doc.getDocumentElement().normalize(); } catch (ParserConfigurationException | SAXException | IOException e) { throw new GrobidPropertyException("Error while manipulating the grobid properties. ", e); } } public String getPassword() { return getValue("password"); } public String getKey() { return getValue("key"); } public String getValue() { return getValue("value"); } public String getType() { return getValue("type"); } /** * Return the value of the pTag. * * @param pTag the tag name. * @return the value contained in the tag. */ protected String getValue(String pTag) { NodeList nList = doc.getElementsByTagName("changeProperty"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; return getTagValue(pTag, eElement); } } return null; } /** * Return the value of the tag pTag in element eElement * * @param sTag the tag name. * @param eElement the element * @return the value contained in the tag. */ protected static String getTagValue(String sTag, Element eElement) { NodeList nlList = eElement.getElementsByTagName(sTag).item(0) .getChildNodes(); Node nValue = (Node) nlList.item(0); return nValue.getNodeValue(); } }
2,649
27.494624
101
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/main/GrobidServiceApplication.java
package org.grobid.service.main; import com.google.common.collect.Lists; import com.google.inject.Module; import com.hubspot.dropwizard.guicier.GuiceBundle; import io.dropwizard.Application; import io.dropwizard.assets.AssetsBundle; import io.dropwizard.forms.MultiPartBundle; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.prometheus.client.dropwizard.DropwizardExports; import io.prometheus.client.exporter.MetricsServlet; import org.apache.commons.lang3.ArrayUtils; import org.eclipse.jetty.servlets.CrossOriginFilter; import org.grobid.service.GrobidServiceConfiguration; import org.grobid.service.modules.GrobidServiceModule; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import javax.servlet.ServletRegistration; import java.io.File; import java.util.Arrays; import java.util.EnumSet; import java.util.List; public final class GrobidServiceApplication extends Application<GrobidServiceConfiguration> { private static final Logger LOGGER = LoggerFactory.getLogger(GrobidServiceApplication.class); private static final String[] DEFAULT_CONF_LOCATIONS = {"grobid-home/config/grobid.yaml"}; private static final String RESOURCES = "/api"; // ========== Application ========== @Override public String getName() { return "grobid-service"; } @Override public void initialize(Bootstrap<GrobidServiceConfiguration> bootstrap) { GuiceBundle<GrobidServiceConfiguration> guiceBundle = GuiceBundle.defaultBuilder(GrobidServiceConfiguration.class) .modules(getGuiceModules()) .build(); bootstrap.addBundle(guiceBundle); bootstrap.addBundle(new MultiPartBundle()); bootstrap.addBundle(new AssetsBundle("/web", "/", "index.html", "grobidAssets")); } private List<? extends Module> getGuiceModules() { return Lists.newArrayList(new GrobidServiceModule()); } @Override public void run(GrobidServiceConfiguration configuration, Environment environment) { LOGGER.info("Service config={}", configuration); new DropwizardExports(environment.metrics()).register(); ServletRegistration.Dynamic registration = environment.admin().addServlet("Prometheus", new MetricsServlet()); registration.addMapping("/metrics/prometheus"); environment.jersey().setUrlPattern(RESOURCES + "/*"); String allowedOrigins = configuration.getGrobid().getCorsAllowedOrigins(); String allowedMethods = configuration.getGrobid().getCorsAllowedMethods(); String allowedHeaders = configuration.getGrobid().getCorsAllowedHeaders(); // Enable CORS headers final FilterRegistration.Dynamic cors = environment.servlets().addFilter("CORS", CrossOriginFilter.class); // Configure CORS parameters cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, allowedOrigins); cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, allowedMethods); cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, allowedHeaders); // Add URL mapping cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, RESOURCES + "/*"); //Error handling // environment.jersey().register(new GrobidExceptionMapper()); // environment.jersey().register(new GrobidServiceExceptionMapper()); // environment.jersey().register(new WebApplicationExceptionMapper()); } // ========== static ========== public static void main(String... args) throws Exception { if (ArrayUtils.getLength(args) < 2) { //LOGGER.warn("Expected 2 argument: [0]-server, [1]-<path to config yaml file>"); String foundConf = null; for (String p : DEFAULT_CONF_LOCATIONS) { File confLocation = new File(p).getAbsoluteFile(); if (confLocation.exists()) { foundConf = confLocation.getAbsolutePath(); LOGGER.info("Found conf path: {}", foundConf); break; } } if (foundConf != null) { LOGGER.warn("Running with default arguments: \"server\" \"{}\"", foundConf); args = new String[]{"server", foundConf}; } else { throw new RuntimeException("No explicit config provided and cannot find in one of the default locations: " + Arrays.toString(DEFAULT_CONF_LOCATIONS)); } } LOGGER.info("Configuration file: {}", new File(args[1]).getAbsolutePath()); new GrobidServiceApplication().run(args); } }
4,765
40.086207
122
java
grobid
grobid-master/grobid-service/src/main/java/org/grobid/service/resources/HealthResource.java
package org.grobid.service.resources; import com.codahale.metrics.health.HealthCheck; import org.grobid.service.GrobidServiceConfiguration; import javax.inject.Inject; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; @Path("health") @Singleton @Produces("application/json;charset=UTF-8") public class HealthResource extends HealthCheck { @Inject private GrobidServiceConfiguration configuration; @Inject public HealthResource() { } @GET public Response alive() { return Response.ok().build(); } @Override protected Result check() throws Exception { return configuration.getGrobid().getGrobidHome() != null ? Result.healthy() : Result.unhealthy("Grobid home is null in the configuration"); } }
870
23.194444
85
java
grobid
grobid-master/grobid-trainer/src/test/java/org/grobid/trainer/AbstractTrainerIntegrationTest.java
package org.grobid.trainer; import org.apache.commons.lang3.tuple.ImmutablePair; import org.grobid.core.GrobidModels; import org.grobid.core.utilities.GrobidProperties; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; public class AbstractTrainerIntegrationTest { private AbstractTrainer target; @BeforeClass public static void init() { GrobidProperties.getInstance(); } @BeforeClass public static void beforeClass() throws Exception { // LibraryLoader.load(); } @Before public void setUp() throws Exception { target = new AbstractTrainer(GrobidModels.DUMMY) { @Override public int createCRFPPData(File corpusPath, File outputTrainingFile, File outputEvalFile, double splitRatio) { // the file for writing the training data // if (outputTrainingFile != null) { // try (OutputStream os = new FileOutputStream(outputTrainingFile)) { // try (Writer writer = new OutputStreamWriter(os, StandardCharsets.UTF_8)) { // // for (int i = 0; i < 100; i++) { // double random = Math.random(); // writer.write("blablabla" + random); // writer.write("\n"); // if (i % 10 == 0) { // writer.write("\n"); // } // } // } // } catch (IOException e) { // e.printStackTrace(); // } // } return 100; } }; } @After public void tearDown() throws Exception { } @Test public void testLoad_shouldWork() throws Exception { Path path = Paths.get("src/test/resources/sample.wapiti.output.date.txt"); List<String> expected = Arrays.asList( "Available available A Av Ava Avai e le ble able LINESTART INITCAP NODIGIT 0 0 0 NOPUNCT I-<other>\n" + "online online o on onl onli e ne ine line LINEIN NOCAPS NODIGIT 0 0 0 NOPUNCT <other>\n" + "18 18 1 18 18 18 8 18 18 18 LINEIN NOCAPS ALLDIGIT 0 0 0 NOPUNCT I-<day>\n" + "January january J Ja Jan Janu y ry ary uary LINEIN INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "2010 2010 2 20 201 2010 0 10 010 2010 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>", "June june J Ju Jun June e ne une June LINESTART INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "16 16 1 16 16 16 6 16 16 16 LINEIN NOCAPS ALLDIGIT 0 0 0 NOPUNCT I-<day>\n" + ", , , , , , , , , , LINEIN ALLCAP NODIGIT 1 0 0 COMMA I-<other>\n" + "2008 2008 2 20 200 2008 8 08 008 2008 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>", "November november N No Nov Nove r er ber mber LINESTART INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "4 4 4 4 4 4 4 4 4 4 LINEIN NOCAPS ALLDIGIT 1 0 0 NOPUNCT I-<day>\n" + ", , , , , , , , , , LINEIN ALLCAP NODIGIT 1 0 0 COMMA I-<other>\n" + "2009 2009 2 20 200 2009 9 09 009 2009 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>", "Published published P Pu Pub Publ d ed hed shed LINESTART INITCAP NODIGIT 0 0 0 NOPUNCT I-<other>\n" + "18 18 1 18 18 18 8 18 18 18 LINEIN NOCAPS ALLDIGIT 0 0 0 NOPUNCT I-<day>\n" + "May may M Ma May May y ay May May LINEIN INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "2011 2011 2 20 201 2011 1 11 011 2011 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>"); List<String> loadedTrainingData = target.load(path); assertThat(loadedTrainingData, is(expected)); } @Test public void testSplitNFold_n3_shouldWork() throws Exception { List<String> dummyTrainingData = new ArrayList<>(); dummyTrainingData.add(dummyExampleGeneration("1", 3)); dummyTrainingData.add(dummyExampleGeneration("2", 4)); dummyTrainingData.add(dummyExampleGeneration("3", 2)); dummyTrainingData.add(dummyExampleGeneration("4", 6)); dummyTrainingData.add(dummyExampleGeneration("5", 6)); dummyTrainingData.add(dummyExampleGeneration("6", 2)); dummyTrainingData.add(dummyExampleGeneration("7", 2)); dummyTrainingData.add(dummyExampleGeneration("8", 3)); dummyTrainingData.add(dummyExampleGeneration("9", 3)); dummyTrainingData.add(dummyExampleGeneration("10", 3)); List<ImmutablePair<String, String>> splitMapping = target.splitNFold(dummyTrainingData, 3); assertThat(splitMapping, hasSize(3)); assertThat(splitMapping.get(0).getLeft(), endsWith("train")); assertThat(splitMapping.get(0).getRight(), endsWith("test")); //Fold 1 List<String> fold1Training = target.load(Paths.get(splitMapping.get(0).getLeft())); List<String> fold1Evaluation = target.load(Paths.get(splitMapping.get(0).getRight())); System.out.println(Arrays.toString(fold1Training.toArray())); System.out.println(Arrays.toString(fold1Evaluation.toArray())); assertThat(fold1Training, hasSize(7)); assertThat(fold1Evaluation, hasSize(3)); //Fold 2 List<String> fold2Training = target.load(Paths.get(splitMapping.get(1).getLeft())); List<String> fold2Evaluation = target.load(Paths.get(splitMapping.get(1).getRight())); System.out.println(Arrays.toString(fold2Training.toArray())); System.out.println(Arrays.toString(fold2Evaluation.toArray())); assertThat(fold2Training, hasSize(7)); assertThat(fold2Evaluation, hasSize(3)); //Fold 3 List<String> fold3Training = target.load(Paths.get(splitMapping.get(2).getLeft())); List<String> fold3Evaluation = target.load(Paths.get(splitMapping.get(2).getRight())); System.out.println(Arrays.toString(fold3Training.toArray())); System.out.println(Arrays.toString(fold3Evaluation.toArray())); assertThat(fold3Training, hasSize(6)); assertThat(fold3Evaluation, hasSize(4)); // Cleanup splitMapping.stream().forEach(f -> { try { Files.delete(Paths.get(f.getRight())); } catch (IOException e) { e.printStackTrace(); } }); splitMapping.stream().forEach(f -> { try { Files.delete(Paths.get(f.getLeft())); } catch (IOException e) { e.printStackTrace(); } }); } @Test(expected = IllegalArgumentException.class) public void testSplitNFold_n10_shouldThrowException() throws Exception { List<String> dummyTrainingData = new ArrayList<>(); dummyTrainingData.add(dummyExampleGeneration("1", 3)); dummyTrainingData.add(dummyExampleGeneration("2", 4)); dummyTrainingData.add(dummyExampleGeneration("3", 2)); dummyTrainingData.add(dummyExampleGeneration("4", 6)); List<ImmutablePair<String, String>> splitMapping = target.splitNFold(dummyTrainingData, 10); } private String dummyExampleGeneration(String exampleId, int total) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < total; i++) { sb.append("line " + i + " example " + exampleId).append("\n"); } sb.append("\n"); return sb.toString(); } @Test public void testLoadAndShuffle_shouldWork() throws Exception { Path path = Paths.get("src/test/resources/sample.wapiti.output.date.txt"); List<String> orderedTrainingData = Arrays.asList( "Available available A Av Ava Avai e le ble able LINESTART INITCAP NODIGIT 0 0 0 NOPUNCT I-<other>\n" + "online online o on onl onli e ne ine line LINEIN NOCAPS NODIGIT 0 0 0 NOPUNCT <other>\n" + "18 18 1 18 18 18 8 18 18 18 LINEIN NOCAPS ALLDIGIT 0 0 0 NOPUNCT I-<day>\n" + "January january J Ja Jan Janu y ry ary uary LINEIN INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "2010 2010 2 20 201 2010 0 10 010 2010 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>", "June june J Ju Jun June e ne une June LINESTART INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "16 16 1 16 16 16 6 16 16 16 LINEIN NOCAPS ALLDIGIT 0 0 0 NOPUNCT I-<day>\n" + ", , , , , , , , , , LINEIN ALLCAP NODIGIT 1 0 0 COMMA I-<other>\n" + "2008 2008 2 20 200 2008 8 08 008 2008 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>", "November november N No Nov Nove r er ber mber LINESTART INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "4 4 4 4 4 4 4 4 4 4 LINEIN NOCAPS ALLDIGIT 1 0 0 NOPUNCT I-<day>\n" + ", , , , , , , , , , LINEIN ALLCAP NODIGIT 1 0 0 COMMA I-<other>\n" + "2009 2009 2 20 200 2009 9 09 009 2009 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>", "Published published P Pu Pub Publ d ed hed shed LINESTART INITCAP NODIGIT 0 0 0 NOPUNCT I-<other>\n" + "18 18 1 18 18 18 8 18 18 18 LINEIN NOCAPS ALLDIGIT 0 0 0 NOPUNCT I-<day>\n" + "May may M Ma May May y ay May May LINEIN INITCAP NODIGIT 0 0 1 NOPUNCT I-<month>\n" + "2011 2011 2 20 201 2011 1 11 011 2011 LINEEND NOCAPS ALLDIGIT 0 1 0 NOPUNCT I-<year>"); List<String> shuffledTrainingData = target.loadAndShuffle(path); assertThat(shuffledTrainingData, hasSize(orderedTrainingData.size())); assertThat(shuffledTrainingData, is(not(orderedTrainingData))); } }
10,190
45.747706
122
java
grobid
grobid-master/grobid-trainer/src/test/java/org/grobid/trainer/StatsTest.java
package org.grobid.trainer; import org.grobid.trainer.evaluation.LabelStat; import org.grobid.trainer.evaluation.Stats; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class StatsTest { Stats target; @Before public void setUp() throws Exception { target = new Stats(); } @Test public void testPrecision_fullMatch() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); assertThat(target.getLabelStat("BAO").getPrecision(), is(1.0)); } @Test public void testPrecision_noMatch() throws Exception { target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); assertThat(target.getLabelStat("MIAO").getPrecision(), is(0.0)); assertThat(target.getLabelStat("MIAO").getSupport(), is(4L)); } @Test public void testPrecision_missingMatch() throws Exception { // The precision stays at 1.0 because none of the observed // is wrong (no false positives) target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); assertThat(target.getLabelStat("CIAO").getPrecision(), is(1.0)); } @Test public void testPrecision_2wronglyRecognised() throws Exception { target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(1); target.getLabelStat("ZIAO").setFalsePositive(2); assertThat(target.getLabelStat("ZIAO").getPrecision(), is(0.3333333333333333)); } @Test public void testRecall_fullMatch() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); assertThat(target.getLabelStat("BAO").getRecall(), is(1.0)); } @Test public void testRecall_noMatch() throws Exception { target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); assertThat(target.getLabelStat("MIAO").getRecall(), is(0.0)); } @Test public void testRecall_oneOverFour() throws Exception { target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); assertThat(target.getLabelStat("CIAO").getRecall(), is(0.25)); } @Test public void testRecall_partialMatch() throws Exception { target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(3); target.getLabelStat("ZIAO").setFalsePositive(1); assertThat(target.getLabelStat("ZIAO").getPrecision(), is(0.75)); } // Average measures @Test public void testMicroAvgPrecision_shouldWork() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(0); target.getLabelStat("ZIAO").setFalsePositive(2); assertThat(target.getMicroAveragePrecision(), is(((double) 4 + 0 + 1 + 0) / (4 + 0 + 3 + 1 + 0 + 2))); } @Test public void testMacroAvgPrecision_shouldWork() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(0); target.getLabelStat("ZIAO").setFalsePositive(2); final double precisionBao = target.getLabelStat("BAO").getPrecision(); final double precisionMiao = target.getLabelStat("MIAO").getPrecision(); final double precisionCiao = target.getLabelStat("CIAO").getPrecision(); final double precisionZiao = target.getLabelStat("ZIAO").getPrecision(); assertThat(target.getMacroAveragePrecision(), is((precisionBao + precisionMiao + precisionCiao + precisionZiao) / (4))); } @Test public void testMicroAvgRecall_shouldWork() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); //TP target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(0); target.getLabelStat("ZIAO").setFalsePositive(2); assertThat(target.getMicroAverageRecall(), is(((double) 4 + 0 + 1 + 0) / (4 + 4 + 4 + 4))); } @Test public void testMacroAvgRecall_shouldWork() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(0); target.getLabelStat("ZIAO").setFalsePositive(2); final double recallBao = target.getLabelStat("BAO").getRecall(); final double recallMiao = target.getLabelStat("MIAO").getRecall(); final double recallCiao = target.getLabelStat("CIAO").getRecall(); final double recallZiao = target.getLabelStat("ZIAO").getRecall(); assertThat(target.getMacroAverageRecall(), is((recallBao + recallMiao + recallCiao + recallZiao) / (4))); } @Test public void testMicroAvgF0_shouldWork() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); //TP target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(0); target.getLabelStat("ZIAO").setFalsePositive(2); assertThat(target.getMicroAverageF1(), is(((double) 2 * target.getMicroAveragePrecision() * target.getMicroAverageRecall()) / (target.getMicroAveragePrecision() + target.getMicroAverageRecall()))); } @Test public void testMacroAvgF0_shouldWork() throws Exception { target.getLabelStat("BAO").setExpected(4); target.getLabelStat("BAO").setObserved(4); target.getLabelStat("MIAO").setExpected(4); target.getLabelStat("MIAO").setObserved(0); target.getLabelStat("MIAO").setFalsePositive(3); target.getLabelStat("MIAO").setFalseNegative(1); target.getLabelStat("CIAO").setExpected(4); target.getLabelStat("CIAO").setObserved(1); target.getLabelStat("CIAO").setFalseNegative(3); target.getLabelStat("ZIAO").setExpected(4); target.getLabelStat("ZIAO").setObserved(0); target.getLabelStat("ZIAO").setFalsePositive(2); final double f1Bao = target.getLabelStat("BAO").getF1Score(); final double f1Miao = target.getLabelStat("MIAO").getF1Score(); final double f1Ciao = target.getLabelStat("CIAO").getF1Score(); final double f1Ziao = target.getLabelStat("ZIAO").getRecall(); assertThat(target.getMacroAverageF1(), is((f1Bao + f1Miao + f1Ciao + f1Ziao) / (4))); } @Ignore("Not really useful") @Test public void testMicroMacroAveragePrecision() throws Exception { final LabelStat conceptual = target.getLabelStat("CONCEPTUAL"); conceptual.setFalsePositive(1); conceptual.setFalseNegative(1); conceptual.setObserved(2); conceptual.setExpected(3); final LabelStat location = target.getLabelStat("LOCATION"); location.setFalsePositive(0); location.setFalseNegative(0); location.setObserved(2); location.setExpected(2); final LabelStat media = target.getLabelStat("MEDIA"); media.setFalsePositive(0); media.setFalseNegative(0); media.setObserved(7); media.setExpected(7); final LabelStat national = target.getLabelStat("NATIONAL"); national.setFalsePositive(1); national.setFalseNegative(0); national.setObserved(0); national.setExpected(0); final LabelStat other = target.getLabelStat("O"); other.setFalsePositive(0); other.setFalseNegative(1); other.setObserved(33); other.setExpected(34); final LabelStat organisation = target.getLabelStat("ORGANISATION"); organisation.setFalsePositive(0); organisation.setFalseNegative(0); organisation.setObserved(2); organisation.setExpected(2); final LabelStat period = target.getLabelStat("PERIOD"); period.setFalsePositive(0); period.setFalseNegative(0); period.setObserved(8); period.setExpected(8); final LabelStat person = target.getLabelStat("PERSON"); person.setFalsePositive(1); person.setFalseNegative(0); person.setObserved(0); person.setExpected(0); final LabelStat personType = target.getLabelStat("PERSON_TYPE"); personType.setFalsePositive(0); personType.setFalseNegative(1); personType.setObserved(0); personType.setExpected(1); for (String label : target.getLabels()) { System.out.println(label + " precision --> " + target.getLabelStat(label).getPrecision()); System.out.println(label + " recall --> " + target.getLabelStat(label).getRecall()); } System.out.println(target.getMacroAveragePrecision()); System.out.println(target.getMicroAveragePrecision()); } @Test public void testMicroMacroAverageMeasures_realTest() throws Exception { LabelStat otherLabelStats = target.getLabelStat("O"); otherLabelStats.setExpected(33); otherLabelStats.setObserved(33); otherLabelStats.setFalseNegative(1); assertThat(otherLabelStats.getPrecision(), is(1.0)); assertThat(otherLabelStats.getRecall(), is(1.0)); LabelStat conceptualLabelStats = target.getLabelStat("CONCEPTUAL"); conceptualLabelStats.setObserved(2); conceptualLabelStats.setExpected(3); conceptualLabelStats.setFalseNegative(1); conceptualLabelStats.setFalsePositive(1); assertThat(conceptualLabelStats.getPrecision(), is(0.6666666666666666)); assertThat(conceptualLabelStats.getRecall(), is(0.6666666666666666)); LabelStat periodLabelStats = target.getLabelStat("PERIOD"); periodLabelStats.setObserved(8); periodLabelStats.setExpected(8); assertThat(periodLabelStats.getPrecision(), is(1.0)); assertThat(periodLabelStats.getRecall(), is(1.0)); LabelStat mediaLabelStats = target.getLabelStat("MEDIA"); mediaLabelStats.setObserved(7); mediaLabelStats.setExpected(7); assertThat(mediaLabelStats.getPrecision(), is(1.0)); assertThat(mediaLabelStats.getRecall(), is(1.0)); LabelStat personTypeLabelStats = target.getLabelStat("PERSON_TYPE"); personTypeLabelStats.setObserved(0); personTypeLabelStats.setExpected(1); personTypeLabelStats.setFalseNegative(1); assertThat(personTypeLabelStats.getPrecision(), is(0.0)); assertThat(personTypeLabelStats.getRecall(), is(0.0)); LabelStat locationTypeLabelStats = target.getLabelStat("LOCATION"); locationTypeLabelStats.setObserved(2); locationTypeLabelStats.setExpected(2); assertThat(locationTypeLabelStats.getPrecision(), is(1.0)); assertThat(locationTypeLabelStats.getRecall(), is(1.0)); LabelStat organisationTypeLabelStats = target.getLabelStat("ORGANISATION"); organisationTypeLabelStats.setObserved(2); organisationTypeLabelStats.setExpected(2); assertThat(locationTypeLabelStats.getPrecision(), is(1.0)); assertThat(locationTypeLabelStats.getRecall(), is(1.0)); LabelStat personLabelStats = target.getLabelStat("PERSON"); personLabelStats.setFalsePositive(1); assertThat(personLabelStats.getPrecision(), is(0.0)); assertThat(personLabelStats.getRecall(), is(0.0)); // 2+8+2+2+7 / (2+8+2+2+7+1) assertThat(target.getMicroAverageRecall(), is(0.9130434782608695)); //91.3 // 2+8+2+2+7 / (3+8+7+2+2+1) assertThat(target.getMicroAveragePrecision(), is(0.9545454545454546)); //95.45 // 0.66 + 1.0 + 1.0 + 0.0 + 1.0 + 1.0 / 6 assertThat(target.getMacroAverageRecall(), is(0.7777777777777777)); //77.78 // same as above assertThat(target.getMacroAveragePrecision(), is(0.7777777777777777)); //77.78 } }
14,740
36.318987
110
java
grobid
grobid-master/grobid-trainer/src/test/java/org/grobid/trainer/evaluation/EvaluationUtilitiesTest.java
package org.grobid.trainer.evaluation; import org.apache.commons.io.IOUtils; import org.hamcrest.core.Is; import org.junit.Test; import java.nio.charset.StandardCharsets; import java.util.TreeMap; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class EvaluationUtilitiesTest { @Test public void testTokenLevelStats_allGood() throws Exception { String result = "a I-<1> I-<1>\nb <1> <1>\nc I-<2> I-<2>\nd I-<1> I-<1>\ne <1> <1>\n"; Stats wordStats = EvaluationUtilities.tokenLevelStats(result); LabelStat labelstat1 = wordStats.getLabelStat("<1>"); LabelStat labelstat2 = wordStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), is(4)); assertThat(labelstat2.getObserved(), is(1)); assertThat(labelstat1.getExpected(), is(4)); assertThat(labelstat2.getExpected(), is(1)); assertThat(labelstat1.getSupport(), is(4L)); assertThat(labelstat2.getSupport(), is(1L)); } @Test public void testTokenLevelStats_noMatch() throws Exception { String result = "a I-<1> I-<2>\nb <1> <2>\nc <1> I-<2>\nd <1> <2>\ne <1> <2>\n"; Stats wordStats = EvaluationUtilities.tokenLevelStats(result); LabelStat labelstat1 = wordStats.getLabelStat("<1>"); LabelStat labelstat2 = wordStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), is(0)); assertThat(labelstat1.getFalseNegative(), is(5)); assertThat(labelstat1.getSupport(), is(5L)); assertThat(labelstat2.getObserved(), is(0)); assertThat(labelstat2.getFalsePositive(), is(5)); assertThat(labelstat2.getSupport(), is(0L)); } @Test public void testTokenLevelStats_mixed() throws Exception { // label of c is false // token 80 precision for label <1>, 0 for label <2> String result = "a I-<1> I-<1>\nb <1> <1>\nc I-<2> <1>\nd I-<1> <1>\ne <1> <1>\n"; //System.out.println(result); Stats wordStats = EvaluationUtilities.tokenLevelStats(result); LabelStat labelstat1 = wordStats.getLabelStat("<1>"); LabelStat labelstat2 = wordStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), is(4)); assertThat(labelstat1.getExpected(), is(4)); assertThat(labelstat1.getFalseNegative(), is(0)); assertThat(labelstat1.getFalsePositive(), is(1)); assertThat(labelstat1.getSupport(), is(4L)); assertThat(labelstat2.getObserved(), is(0)); assertThat(labelstat2.getExpected(), is(1)); assertThat(labelstat2.getFalseNegative(), is(1)); assertThat(labelstat2.getFalsePositive(), is(0)); assertThat(labelstat2.getSupport(), is(1L)); } @Test public void testTokenLevelStats2_mixed() throws Exception { String result = "a I-<1> I-<1>\nb <1> <1>\nc I-<2> I-<1>\nd I-<1> <1>\ne <1> <1>\n"; Stats wordStats = EvaluationUtilities.tokenLevelStats(result); LabelStat labelstat1 = wordStats.getLabelStat("<1>"); LabelStat labelstat2 = wordStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), is(4)); assertThat(labelstat1.getExpected(), is(4)); assertThat(labelstat1.getFalseNegative(), is(0)); assertThat(labelstat1.getFalsePositive(), is(1)); assertThat(labelstat1.getSupport(), is(4L)); assertThat(labelstat2.getObserved(), is(0)); assertThat(labelstat2.getExpected(), is(1)); assertThat(labelstat2.getFalseNegative(), is(1)); assertThat(labelstat2.getFalsePositive(), is(0)); assertThat(labelstat2.getSupport(), is(1L)); } @Test public void testTokenLevelStats3_mixed() throws Exception { String result = "a I-<1> I-<1>\nb <1> <1>\nc <1> I-<2>\nd <1> I-<1>\ne <1> <1>\n"; //System.out.println(result); Stats wordStats = EvaluationUtilities.tokenLevelStats(result); LabelStat labelstat1 = wordStats.getLabelStat("<1>"); LabelStat labelstat2 = wordStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), is(4)); assertThat(labelstat2.getObserved(), is(0)); assertThat(labelstat1.getExpected(), is(5)); assertThat(labelstat2.getExpected(), is(0)); assertThat(labelstat1.getFalseNegative(), is(1)); assertThat(labelstat2.getFalseNegative(), is(0)); assertThat(labelstat1.getFalsePositive(), is(0)); assertThat(labelstat2.getFalsePositive(), is(1)); } @Test public void testTokenLevelStats4_mixed() throws Exception { String result = "a I-<1> I-<1>\nb I-<2> <1>\nc <2> I-<2>\nd <2> <2>\ne I-<1> I-<1>\nf <1> <1>\ng I-<2> I-<2>\n"; Stats wordStats = EvaluationUtilities.tokenLevelStats(result); LabelStat labelstat1 = wordStats.getLabelStat("<1>"); LabelStat labelstat2 = wordStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), is(3)); assertThat(labelstat1.getExpected(), is(3)); assertThat(labelstat1.getFalseNegative(), is(0)); assertThat(labelstat1.getFalsePositive(), is(1)); assertThat(labelstat2.getObserved(), is(3)); assertThat(labelstat2.getExpected(), is(4)); assertThat(labelstat2.getFalseNegative(), is(1)); assertThat(labelstat2.getFalsePositive(), is(0)); } @Test public void testTokenLevelStats_realCase() throws Exception { String result = IOUtils.toString(this.getClass().getResourceAsStream("/sample.wapiti.output.1.txt"), StandardCharsets.UTF_8); result = result.replace(System.lineSeparator(), "\n"); Stats wordStats = EvaluationUtilities.tokenLevelStats(result); LabelStat labelstat1 = wordStats.getLabelStat("<body>"); LabelStat labelstat2 = wordStats.getLabelStat("<headnote>"); assertThat(labelstat1.getObserved(), is(378)); assertThat(labelstat2.getObserved(), is(6)); assertThat(labelstat1.getExpected(), is(378)); assertThat(labelstat2.getExpected(), is(9)); assertThat(labelstat1.getFalseNegative(), is(0)); assertThat(labelstat2.getFalseNegative(), is(3)); assertThat(labelstat1.getFalsePositive(), is(3)); assertThat(labelstat2.getFalsePositive(), is(0)); } @Test public void testTokenLevelStats2_realCase() throws Exception { String result = IOUtils.toString(this.getClass().getResourceAsStream("/sample.wapiti.output.2.txt"), StandardCharsets.UTF_8); Stats stats = EvaluationUtilities.tokenLevelStats(result); LabelStat conceptualLabelStats = stats.getLabelStat("CONCEPTUAL"); assertThat(conceptualLabelStats.getObserved(), is(2)); assertThat(conceptualLabelStats.getExpected(), is(3)); assertThat(conceptualLabelStats.getFalseNegative(), is(1)); assertThat(conceptualLabelStats.getFalsePositive(), is(1)); LabelStat periodLabelStats = stats.getLabelStat("PERIOD"); assertThat(periodLabelStats.getObserved(), is(8)); assertThat(periodLabelStats.getExpected(), is(8)); assertThat(periodLabelStats.getFalseNegative(), is(0)); assertThat(periodLabelStats.getFalsePositive(), is(0)); LabelStat mediaLabelStats = stats.getLabelStat("MEDIA"); assertThat(mediaLabelStats.getObserved(), is(7)); assertThat(mediaLabelStats.getExpected(), is(7)); assertThat(mediaLabelStats.getFalseNegative(), is(0)); assertThat(mediaLabelStats.getFalsePositive(), is(0)); LabelStat personTypeLabelStats = stats.getLabelStat("PERSON_TYPE"); assertThat(personTypeLabelStats.getObserved(), is(0)); assertThat(personTypeLabelStats.getExpected(), is(1)); assertThat(personTypeLabelStats.getFalseNegative(), is(1)); assertThat(personTypeLabelStats.getFalsePositive(), is(0)); LabelStat locationTypeLabelStats = stats.getLabelStat("LOCATION"); assertThat(locationTypeLabelStats.getObserved(), is(2)); assertThat(locationTypeLabelStats.getExpected(), is(2)); assertThat(locationTypeLabelStats.getFalseNegative(), is(0)); assertThat(locationTypeLabelStats.getFalsePositive(), is(0)); LabelStat organisationTypeLabelStats = stats.getLabelStat("ORGANISATION"); assertThat(organisationTypeLabelStats.getObserved(), is(2)); assertThat(organisationTypeLabelStats.getExpected(), is(2)); assertThat(organisationTypeLabelStats.getFalseNegative(), is(0)); assertThat(organisationTypeLabelStats.getFalsePositive(), is(0)); LabelStat otherLabelStats = stats.getLabelStat("O"); assertThat(otherLabelStats.getObserved(), is(33)); assertThat(otherLabelStats.getExpected(), is(34)); assertThat(otherLabelStats.getFalseNegative(), is(1)); assertThat(otherLabelStats.getFalsePositive(), is(0)); LabelStat personLabelStats = stats.getLabelStat("PERSON"); assertThat(personLabelStats.getObserved(), is(0)); assertThat(personLabelStats.getExpected(), is(0)); assertThat(personLabelStats.getFalseNegative(), is(0)); assertThat(personLabelStats.getFalsePositive(), is(1)); } @Test public void testTokenLevelStats4_realCase() throws Exception { String result = IOUtils.toString(this.getClass().getResourceAsStream("/sample.wapiti.output.3.txt"), StandardCharsets.UTF_8); ModelStats fieldStats = EvaluationUtilities.computeStats(result); assertThat(fieldStats.getTotalInstances(), is(4)); assertThat(fieldStats.getCorrectInstance(), is(1)); assertThat(fieldStats.getInstanceRecall(), is(1.0/4)); assertThat(fieldStats.getSupportSum(), is(6L)); } }
9,783
41.912281
133
java
grobid
grobid-master/grobid-trainer/src/test/java/org/grobid/trainer/evaluation/EndToEndEvaluationTest.java
package org.grobid.trainer.evaluation; import org.grobid.trainer.evaluation.utilities.FieldSpecification; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; public class EndToEndEvaluationTest { @Test public void testRemoveFieldsFromEvaluation_shouldRemove() throws Exception { List<FieldSpecification> fieldSpecification = new ArrayList<>(); FieldSpecification field1 = new FieldSpecification(); field1.fieldName = "bao"; fieldSpecification.add(field1); FieldSpecification field2 = new FieldSpecification(); field2.fieldName = "miao"; fieldSpecification.add(field2); List<String> labelSpecification = new ArrayList<>(); labelSpecification.add("bao"); labelSpecification.add("miao"); EndToEndEvaluation.removeFieldsFromEvaluation(Arrays.asList("bao"), fieldSpecification, labelSpecification); assertThat(fieldSpecification, hasSize(1)); assertThat(labelSpecification, hasSize(1)); assertThat(fieldSpecification.get(0).fieldName, is("miao")); assertThat(labelSpecification.get(0), is("miao")); } @Test public void testRemoveFieldsFromEvaluation() throws Exception { List<FieldSpecification> fieldSpecification = new ArrayList<>(); FieldSpecification field1 = new FieldSpecification(); field1.fieldName = "bao"; fieldSpecification.add(field1); FieldSpecification field2 = new FieldSpecification(); field2.fieldName = "miao"; fieldSpecification.add(field2); List<String> labelSpecification = new ArrayList<>(); labelSpecification.add("bao"); labelSpecification.add("miao"); EndToEndEvaluation.removeFieldsFromEvaluation(Arrays.asList("zao"), fieldSpecification, labelSpecification); assertThat(fieldSpecification, hasSize(2)); assertThat(labelSpecification, hasSize(2)); assertThat(fieldSpecification.get(0).fieldName, is("bao")); assertThat(labelSpecification.get(0), is("bao")); assertThat(fieldSpecification.get(1).fieldName, is("miao")); assertThat(labelSpecification.get(1), is("miao")); } @Test public void testRemoveFieldsFromEvaluationEmpty_ShouldNotFail() throws Exception { List<FieldSpecification> fieldSpecification = new ArrayList<>(); List<String> labelSpecification = new ArrayList<>(); EndToEndEvaluation.removeFieldsFromEvaluation(Arrays.asList("bao"), fieldSpecification, labelSpecification); assertThat(fieldSpecification, hasSize(0)); assertThat(labelSpecification, hasSize(0)); } }
2,834
34.4375
116
java
grobid
grobid-master/grobid-trainer/src/test/java/org/grobid/trainer/evaluation/ModelStatsTest.java
package org.grobid.trainer.evaluation; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.Pair; import org.hamcrest.CoreMatchers; import org.junit.Before; import org.junit.Test; import java.nio.charset.StandardCharsets; import java.util.TreeMap; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class ModelStatsTest { ModelStats target; @Before public void setUp() throws Exception { target = new ModelStats(); } @Test public void test_empty() throws Exception { assertThat(target.getInstanceRecall(), is(0.0)); } @Test public void testInstantiation_realCase() throws Exception { String result = IOUtils.toString(this.getClass().getResourceAsStream("/sample.wapiti.output.3.txt"), StandardCharsets.UTF_8); Pair<Integer, Integer> instanceStatistics = target.computeInstanceStatistics(result); assertThat(instanceStatistics.getRight(), is(1)); assertThat(instanceStatistics.getLeft(), is(4)); } @Test public void testTokenLevelStats3_realCase() throws Exception { String result = IOUtils.toString(this.getClass().getResourceAsStream("/sample.wapiti.output.3.txt"), StandardCharsets.UTF_8); Stats fieldStats = target.fieldLevelStats(result); TreeMap<String, LabelResult> labelsResults = fieldStats.getLabelsResults(); assertThat(labelsResults.get("<base>").getSupport(), CoreMatchers.is(4L)); assertThat(labelsResults.get("<prefix>").getSupport(), CoreMatchers.is(2L)); } @Test public void testFieldLevelStats_realCase() throws Exception { String result = IOUtils.toString(this.getClass().getResourceAsStream("/sample.wapiti.output.1.txt"), StandardCharsets.UTF_8); Stats fieldStats = target.fieldLevelStats(result); LabelStat labelstat1 = fieldStats.getLabelStat("<body>"); LabelStat labelstat2 = fieldStats.getLabelStat("<headnote>"); assertThat(labelstat1.getObserved(), CoreMatchers.is(1)); assertThat(labelstat2.getObserved(), CoreMatchers.is(2)); assertThat(labelstat1.getExpected(), CoreMatchers.is(3)); assertThat(labelstat2.getExpected(), CoreMatchers.is(3)); assertThat(labelstat1.getFalseNegative(), CoreMatchers.is(2)); assertThat(labelstat2.getFalseNegative(), CoreMatchers.is(1)); assertThat(labelstat1.getFalsePositive(), CoreMatchers.is(1)); assertThat(labelstat2.getFalsePositive(), CoreMatchers.is(0)); } @Test public void testFieldLevelStats4_mixed() throws Exception { String result = "a I-<1> I-<1>\nb I-<2> <1>\nc <2> I-<2>\nd <2> <2>\ne I-<1> I-<1>\nf <1> <1>\ng I-<2> I-<2>\n"; Stats fieldStats = target.fieldLevelStats(result); LabelStat labelstat1 = fieldStats.getLabelStat("<1>"); LabelStat labelstat2 = fieldStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), CoreMatchers.is(1)); assertThat(labelstat2.getObserved(), CoreMatchers.is(1)); assertThat(labelstat1.getExpected(), CoreMatchers.is(2)); assertThat(labelstat2.getExpected(), CoreMatchers.is(2)); assertThat(labelstat1.getFalseNegative(), CoreMatchers.is(1)); assertThat(labelstat2.getFalseNegative(), CoreMatchers.is(1)); assertThat(labelstat1.getFalsePositive(), CoreMatchers.is(1)); assertThat(labelstat2.getFalsePositive(), CoreMatchers.is(1)); } @Test public void testFieldLevelStats3_mixed() throws Exception { String result = "a I-<1> I-<1>\nb <1> <1>\nc <1> I-<2>\nd <1> I-<1>\ne <1> <1>\n"; Stats fieldStats = target.fieldLevelStats(result); LabelStat labelstat1 = fieldStats.getLabelStat("<1>"); LabelStat labelstat2 = fieldStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), CoreMatchers.is(0)); assertThat(labelstat2.getObserved(), CoreMatchers.is(0)); assertThat(labelstat1.getExpected(), CoreMatchers.is(1)); assertThat(labelstat2.getExpected(), CoreMatchers.is(0)); assertThat(labelstat1.getFalseNegative(), CoreMatchers.is(1)); assertThat(labelstat2.getFalseNegative(), CoreMatchers.is(0)); assertThat(labelstat1.getFalsePositive(), CoreMatchers.is(2)); assertThat(labelstat2.getFalsePositive(), CoreMatchers.is(1)); } @Test public void testFieldLevelStats2_mixed() throws Exception { // variant of testMetricsMixed1 where the I- prefix impact the field-level results // with field ab correctly found String result = "a I-<1> I-<1>\nb <1> <1>\nc I-<2> I-<1>\nd I-<1> <1>\ne <1> <1>\n"; Stats fieldStats = target.fieldLevelStats(result); LabelStat labelstat1 = fieldStats.getLabelStat("<1>"); LabelStat labelstat2 = fieldStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), CoreMatchers.is(1)); assertThat(labelstat1.getExpected(), CoreMatchers.is(2)); assertThat(labelstat2.getObserved(), CoreMatchers.is(0)); assertThat(labelstat2.getExpected(), CoreMatchers.is(1)); } @Test public void testFieldLevelStats_allGood() throws Exception { String result = "a I-<1> I-<1>\nb <1> <1>\nc I-<2> I-<2>\nd I-<1> I-<1>\ne <1> <1>\n"; Stats fieldStats = target.fieldLevelStats(result); LabelStat labelstat1 = fieldStats.getLabelStat("<1>"); LabelStat labelstat2 = fieldStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), CoreMatchers.is(2)); assertThat(labelstat2.getObserved(), CoreMatchers.is(1)); assertThat(labelstat1.getExpected(), CoreMatchers.is(2)); assertThat(labelstat2.getExpected(), CoreMatchers.is(1)); assertThat(labelstat1.getSupport(), CoreMatchers.is(2L)); assertThat(labelstat2.getSupport(), CoreMatchers.is(1L)); } @Test public void testFieldLevelStats_noMatch() throws Exception { String result = "a I-<1> I-<2>\nb <1> <2>\nc <1> I-<2>\nd <1> <2>\ne <1> <2>\n"; Stats fieldStats = target.fieldLevelStats(result); LabelStat labelstat1 = fieldStats.getLabelStat("<1>"); LabelStat labelstat2 = fieldStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), CoreMatchers.is(0)); assertThat(labelstat1.getExpected(), CoreMatchers.is(1)); assertThat(labelstat1.getSupport(), CoreMatchers.is(1L)); assertThat(labelstat2.getObserved(), CoreMatchers.is(0)); assertThat(labelstat2.getExpected(), CoreMatchers.is(0)); assertThat(labelstat2.getSupport(), CoreMatchers.is(0L)); } @Test public void testFieldLevelStats_mixed() throws Exception { // field: precision and recall are 0, because the whole // sequence abcde with label <1> does not make sub-field // ab and de correctly label with respect to positions String result = "a I-<1> I-<1>\nb <1> <1>\nc I-<2> <1>\nd I-<1> <1>\ne <1> <1>\n"; Stats fieldStats = target.fieldLevelStats(result); LabelStat labelstat1 = fieldStats.getLabelStat("<1>"); LabelStat labelstat2 = fieldStats.getLabelStat("<2>"); assertThat(labelstat1.getObserved(), CoreMatchers.is(0)); assertThat(labelstat1.getExpected(), CoreMatchers.is(2)); assertThat(labelstat1.getSupport(), CoreMatchers.is(2L)); assertThat(labelstat2.getObserved(), CoreMatchers.is(0)); assertThat(labelstat2.getExpected(), CoreMatchers.is(1)); assertThat(labelstat2.getSupport(), CoreMatchers.is(1L)); } }
7,622
41.116022
133
java
grobid
grobid-master/grobid-trainer/src/test/java/org/grobid/trainer/sax/TEICitationSaxParserTest.java
package org.grobid.trainer.sax; import org.junit.Before; import org.junit.Test; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.InputStream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; public class TEICitationSaxParserTest { TEICitationSaxParser target; SAXParserFactory spf; @Before public void setUp() throws Exception { spf = SAXParserFactory.newInstance(); target = new TEICitationSaxParser(); } @Test public void testCitation() throws Exception { InputStream is = this.getClass().getResourceAsStream("/31-1708.04410.training.references.tei.xml"); final SAXParser p = spf.newSAXParser(); p.parse(is, target); assertThat(target.getLabeledResult(), hasSize(25)); assertThat(target.getLabeledResult().get(0), hasSize(49)); assertThat(target.getLabeledResult().get(0).get(0).toString(), is("I-<author>")); assertThat(target.getTokensResult().get(0).get(0).toString(), is("H")); assertThat(target.getLabeledResult().get(0).get(1).toString(), is("<author>")); assertThat(target.getTokensResult().get(0).get(1).toString(), is(".")); } }
1,300
29.255814
107
java
grobid
grobid-master/grobid-trainer/src/main/java/org/grobid/trainer/DummyTrainer.java
package org.grobid.trainer; import org.grobid.core.GrobidModel; import java.io.File; /** * Dummy trainer which won't do anything. */ public class DummyTrainer implements GenericTrainer { @Override public void train(File template, File trainingData, File outputModel, int numThreads, GrobidModel model) { } @Override public void train(File template, File trainingData, File outputModel, int numThreads, GrobidModel model, boolean incremental) { } @Override public String getName() { return null; } @Override public void setEpsilon(double epsilon) { } @Override public void setWindow(int window) { } @Override public double getEpsilon() { return 0; } @Override public int getWindow() { return 0; } @Override public int getNbMaxIterations() { return 0; } @Override public void setNbMaxIterations(int iterations) { } }
973
16.392857
131
java
grobid
grobid-master/grobid-trainer/src/main/java/org/grobid/trainer/Trainer.java
package org.grobid.trainer; import org.grobid.core.GrobidModel; import org.grobid.core.GrobidModels; import org.grobid.core.engines.tagging.GenericTagger; import java.io.File; public interface Trainer { int createCRFPPData(File corpusPath, File outputFile); int createCRFPPData(File corpusPath, File outputTrainingFile, File outputEvalFile, double splitRatio); void train(); void train(boolean incremental); String evaluate(); String evaluate(boolean includeRawResults); String evaluate(GenericTagger tagger, boolean includeRawResults); String splitTrainEvaluate(Double split); String splitTrainEvaluate(Double split, boolean incremental); String nFoldEvaluate(int folds); String nFoldEvaluate(int folds, boolean includeRawResults); GrobidModel getModel(); }
809
22.823529
103
java
grobid
grobid-master/grobid-trainer/src/main/java/org/grobid/trainer/DeLFTTrainer.java
package org.grobid.trainer; import org.grobid.core.GrobidModel; import org.grobid.core.jni.DeLFTModel; import org.grobid.core.GrobidModels; import org.grobid.trainer.SegmentationTrainer; import org.grobid.core.utilities.GrobidProperties; import java.math.BigDecimal; import java.io.File; public class DeLFTTrainer implements GenericTrainer { public static final String DELFT = "delft"; @Override public void train(File template, File trainingData, File outputModel, int numThreads, GrobidModel model) { train(template, trainingData, outputModel, numThreads, model, false); } @Override public void train(File template, File trainingData, File outputModel, int numThreads, GrobidModel model, boolean incremental) { DeLFTModel.train(model.getModelName(), trainingData, outputModel, GrobidProperties.getDelftArchitecture(model), incremental); } @Override public String getName() { return DELFT; } /** * None of this below is used by DeLFT */ @Override public void setEpsilon(double epsilon) { } @Override public void setWindow(int window) { } @Override public double getEpsilon() { return 0.0; } @Override public int getWindow() { return 0; } @Override public void setNbMaxIterations(int interations) { } @Override public int getNbMaxIterations() { return 0; } }
1,466
23.04918
133
java
grobid
grobid-master/grobid-trainer/src/main/java/org/grobid/trainer/AffiliationAddressTrainer.java
package org.grobid.trainer; import org.grobid.core.GrobidModels; import org.grobid.core.exceptions.GrobidException; import org.grobid.core.features.FeaturesVectorAffiliationAddress; import org.grobid.core.layout.LayoutToken; import org.grobid.core.utilities.GrobidProperties; import org.grobid.core.utilities.OffsetPosition; import org.grobid.trainer.sax.TEIAffiliationAddressSaxParser; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.List; public class AffiliationAddressTrainer extends AbstractTrainer { public AffiliationAddressTrainer() { super(GrobidModels.AFFILIATION_ADDRESS); } /** * Add the selected features to an affiliation/address example set * * @param corpusDir * a path where corpus files are located * @param trainingOutputPath * path where to store the temporary training data * @return the total number of used corpus items */ @Override public int createCRFPPData(final File corpusDir, final File trainingOutputPath) { return createCRFPPData(corpusDir, trainingOutputPath, null, 1.0); } /** * Add the selected features to an affiliation/address example set * * @param corpusDir * a path where corpus files are located * @param trainingOutputPath * path where to store the temporary training data * @param evalOutputPath * path where to store the temporary evaluation data * @param splitRatio * ratio to consider for separating training and evaluation data, e.g. 0.8 for 80% * @return the total number of used corpus items */ @Override public int createCRFPPData(final File corpusDir, final File trainingOutputPath, final File evalOutputPath, double splitRatio) { int totalExamples = 0; try { System.out.println("sourcePathLabel: " + corpusDir); if (trainingOutputPath != null) System.out.println("outputPath for training data: " + trainingOutputPath); if (evalOutputPath != null) System.out.println("outputPath for evaluation data: " + evalOutputPath); // we convert the tei files into the usual CRF label format // we process all tei files in the output directory final File[] refFiles = corpusDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".xml"); } }); if (refFiles == null) { throw new IllegalStateException("Folder " + corpusDir.getAbsolutePath() + " does not seem to contain training data. Please check"); } System.out.println(refFiles.length + " tei files"); // the file for writing the training data OutputStream os2 = null; Writer writer2 = null; if (trainingOutputPath != null) { os2 = new FileOutputStream(trainingOutputPath); writer2 = new OutputStreamWriter(os2, "UTF8"); } // the file for writing the evaluation data OutputStream os3 = null; Writer writer3 = null; if (evalOutputPath != null) { os3 = new FileOutputStream(evalOutputPath); writer3 = new OutputStreamWriter(os3, "UTF8"); } // get a factory for SAX parser SAXParserFactory spf = SAXParserFactory.newInstance(); List<List<OffsetPosition>> placesPositions = null; List<List<LayoutToken>> allTokens = null; int n = 0; for (; n < refFiles.length; n++) { final File teifile = refFiles[n]; String name = teifile.getName(); //System.out.println(name); final TEIAffiliationAddressSaxParser parser2 = new TEIAffiliationAddressSaxParser(); // get a new instance of parser final SAXParser p = spf.newSAXParser(); p.parse(teifile, parser2); final List<String> labeled = parser2.getLabeledResult(); allTokens = parser2.getAllTokens(); placesPositions = parser2.getPlacesPositions(); totalExamples += parser2.n; // we can now add the features String affAdd = FeaturesVectorAffiliationAddress .addFeaturesAffiliationAddress(labeled, allTokens, placesPositions); // format with features for sequence tagging... // given the split ratio we write either in the training file or the evaluation file //affAdd = affAdd.replace("\n \n", "\n \n"); String[] chunks = affAdd.split("\n\n"); for(int i=0; i<chunks.length; i++) { String chunk = chunks[i]; if ( (writer2 == null) && (writer3 != null) ) writer3.write(chunk + "\n \n"); if ( (writer2 != null) && (writer3 == null) ) writer2.write(chunk + "\n \n"); else { if (Math.random() <= splitRatio) writer2.write(chunk + "\n \n"); else writer3.write(chunk + "\n \n"); } } } if (writer2 != null) { writer2.close(); os2.close(); } if (writer3 != null) { writer3.close(); os3.close(); } } catch (Exception e) { throw new GrobidException("An exception occurred while running Grobid.", e); } return totalExamples; } /** * Command line execution. * * @param args Command line arguments. * @throws Exception */ public static void main(String[] args) throws Exception { GrobidProperties.getInstance(); Trainer trainer = new AffiliationAddressTrainer(); AbstractTrainer.runTraining(trainer); System.out.println(AbstractTrainer.runEvaluation(trainer)); System.exit(0); } }
5,602
30.655367
95
java
grobid
grobid-master/grobid-trainer/src/main/java/org/grobid/trainer/ChemicalEntityTrainer.java
package org.grobid.trainer; import org.grobid.core.GrobidModels; import org.grobid.core.exceptions.GrobidException; import org.grobid.core.features.FeaturesVectorChemicalEntity; import org.grobid.core.utilities.OffsetPosition; import org.grobid.trainer.sax.*; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.*; import java.util.ArrayList; import java.util.List; public class ChemicalEntityTrainer extends AbstractTrainer { public ChemicalEntityTrainer() { super(GrobidModels.ENTITIES_CHEMISTRY); } /** * Add the selected features to a chemical entity example set * * @param corpusDir * a path where corpus files are located * @param trainingOutputPath * path where to store the temporary training data * @return the total number of used corpus items */ public int createCRFPPData2(final File corpusDir, final File modelOutputPath) { return createCRFPPData(corpusDir, modelOutputPath, null, 1.0); } /** * Add the selected features to a chemical entity example set * * @param corpusDir * a path where corpus files are located * @param trainingOutputPath * path where to store the temporary training data * @param evalOutputPath * path where to store the temporary evaluation data * @param splitRatio * ratio to consider for separating training and evaluation data, e.g. 0.8 for 80% * @return the total number of corpus items */ @Override public int createCRFPPData(final File corpusDir, final File trainingOutputPath, final File evalOutputPath, double splitRatio) { return 0; } /** * Add the selected features to a chemical entity example set * * @param corpusDir * a path where corpus files are located * @param trainingOutputPath * path where to store the temporary training data * @return the total number of used corpus items */ @Override public int createCRFPPData(File corpusDir, File trainingOutputPath) { int totalExamples = 0; try { System.out.println("corpusDir: " + corpusDir); System.out.println("trainingOutputPath: " + trainingOutputPath); // then we convert the tei files into the usual CRF label format // we process all tei files in the output directory File[] refFiles = corpusDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".words.xml") && name.startsWith("WO"); } }); if (refFiles == null) { return 0; } System.out.println(refFiles.length + " tei files"); // the file for writing the training data Writer writer2 = new OutputStreamWriter(new FileOutputStream(trainingOutputPath), "UTF8"); // get a factory for SAX parser SAXParserFactory spf = SAXParserFactory.newInstance(); String name; ArrayList<ArrayList<String>> chemicalAnnotations = null; ArrayList<ArrayList<String>> chemicalFormulas = null; ArrayList<ArrayList<String>> chemicalSubstances = null; ArrayList<ArrayList<String>> chemicalClassNames = null; ArrayList<ArrayList<String>> chemicalLigand = null; int n = 0; for (; n < refFiles.length; n++) { File thefile = refFiles[n]; if (thefile.getName().endsWith(".words.xml")) { // chemical names name = thefile.getName().replace(".words.xml", ""); System.out.println(name); File theOtherFile = new File(thefile.getPath().replace(".words.xml", ".HC.chemical-names.xml")); if (theOtherFile.exists()) { // get the chemical names first ChemicalNameSaxParser parser2 = new ChemicalNameSaxParser(); //get a new instance of parser SAXParser p = spf.newSAXParser(); p.parse(thefile, parser2); chemicalAnnotations = parser2.getChemicalAnnotations(); totalExamples += parser2.getNumberEntities(); } theOtherFile = new File(thefile.getPath().replace(".words.xml", ".HC.formula-names.xml")); if (theOtherFile.exists()) { ChemicalFormulasSaxParser parser3 = new ChemicalFormulasSaxParser(); //get a new instance of parser SAXParser p2 = spf.newSAXParser(); p2.parse(theOtherFile, parser3); chemicalFormulas = parser3.getChemicalFormulas(); totalExamples += parser3.getNumberEntities(); } theOtherFile = new File(thefile.getPath().replace(".words.xml", ".HC.substance-names.xml")); if (theOtherFile.exists()) { ChemicalSubstancesSaxParser parser4 = new ChemicalSubstancesSaxParser(); //get a new instance of parser SAXParser p2 = spf.newSAXParser(); p2.parse(theOtherFile, parser4); chemicalSubstances = parser4.getChemicalSubstances(); totalExamples += parser4.getNumberEntities(); } theOtherFile = new File(thefile.getPath().replace(".words.xml", ".HC.class-names.xml")); if (theOtherFile.exists()) { ChemicalClassNamesSaxParser parser5 = new ChemicalClassNamesSaxParser(); //get a new instance of parser SAXParser p2 = spf.newSAXParser(); p2.parse(theOtherFile, parser5); chemicalClassNames = parser5.getChemicalClassNames(); totalExamples += parser5.getNumberEntities(); } theOtherFile = new File(thefile.getPath().replace(".words.xml", ".HC.ligand.xml")); if (theOtherFile.exists()) { ChemicalLigandSaxParser parser6 = new ChemicalLigandSaxParser(); //get a new instance of parser SAXParser p2 = spf.newSAXParser(); p2.parse(theOtherFile, parser6); chemicalLigand = parser6.getChemicalLigand(); totalExamples += parser6.getNumberEntities(); } } List<String> chemicalAnnotationsList = new ArrayList<String>(); List<String> chemicalAnnotationsStartsList = new ArrayList<String>(); if (chemicalAnnotations != null) { for (ArrayList<String> toto : chemicalAnnotations) { String first = toto.get(0).trim(); String last = toto.get(1).trim(); // double check first and last order if (first.length() > last.length()) { last = toto.get(0); first = toto.get(1); } else if ((first.length() == last.length()) && (first.compareToIgnoreCase(last) > 0)) { last = toto.get(0); first = toto.get(1); } chemicalAnnotationsStartsList.add(first); if (!last.equals(first)) { String next = first; while (!next.equals(last)) { int ind = next.lastIndexOf("_"); String numb = next.substring(ind + 1, next.length()); try { Integer numbi = Integer.parseInt(numb); next = next.substring(0, ind + 1) + (numbi + 1); } catch (NumberFormatException e) { throw new GrobidException("An exception occured while running Grobid.", e); } if (!next.equals(first)) { chemicalAnnotationsList.add(next); } } } chemicalAnnotationsList.add(last); } } List<String> chemicalFormulasList = new ArrayList<String>(); List<String> chemicalFormulasStartsList = new ArrayList<String>(); if (chemicalFormulas != null) { for (ArrayList<String> toto : chemicalFormulas) { String first = toto.get(0).trim(); String last = toto.get(1).trim(); // double check first and last order if (first.length() > last.length()) { last = toto.get(0); first = toto.get(1); } else if ((first.length() == last.length()) && (first.compareToIgnoreCase(last) > 0)) { last = toto.get(0); first = toto.get(1); } chemicalFormulasStartsList.add(first); if (!last.equals(first)) { String next = first; while (!next.equals(last)) { int ind = next.lastIndexOf("_"); String numb = next.substring(ind + 1, next.length()); try { Integer numbi = Integer.parseInt(numb); next = next.substring(0, ind + 1) + (numbi + 1); } catch (NumberFormatException e) { throw new GrobidException("An exception occured while running Grobid.", e); } if (!next.equals(first)) { chemicalFormulasList.add(next); } } } chemicalFormulasList.add(last); } } List<String> chemicalSubstancesList = new ArrayList<String>(); List<String> chemicalSubstancesStartsList = new ArrayList<String>(); if (chemicalSubstances != null) { for (ArrayList<String> toto : chemicalSubstances) { String first = toto.get(0).trim(); String last = toto.get(1).trim(); // double check first and last order if (first.length() > last.length()) { last = toto.get(0); first = toto.get(1); } else if ((first.length() == last.length()) && (first.compareToIgnoreCase(last) > 0)) { last = toto.get(0); first = toto.get(1); } chemicalSubstancesStartsList.add(first); if (!last.equals(first)) { String next = first; while (!next.equals(last)) { int ind = next.lastIndexOf("_"); String numb = next.substring(ind + 1, next.length()); try { Integer numbi = Integer.parseInt(numb); next = next.substring(0, ind + 1) + (numbi + 1); } catch (NumberFormatException e) { throw new GrobidException("An exception occured while running Grobid.", e); } if (!next.equals(first)) { chemicalSubstancesList.add(next); } } } chemicalSubstancesList.add(last); } } List<String> chemicalClassNamesList = new ArrayList<String>(); List<String> chemicalClassNamesStartsList = new ArrayList<String>(); if (chemicalClassNames != null) { for (ArrayList<String> toto : chemicalClassNames) { String first = toto.get(0).trim(); String last = toto.get(1).trim(); // double check first and last order if (first.length() > last.length()) { last = toto.get(0); first = toto.get(1); } else if ((first.length() == last.length()) && (first.compareToIgnoreCase(last) > 0)) { last = toto.get(0); first = toto.get(1); } chemicalClassNamesStartsList.add(first); if (!last.equals(first)) { String next = first; while (!next.equals(last)) { int ind = next.lastIndexOf("_"); String numb = next.substring(ind + 1, next.length()); try { Integer numbi = Integer.parseInt(numb); next = next.substring(0, ind + 1) + (numbi + 1); } catch (NumberFormatException e) { throw new GrobidException("An exception occured while running Grobid.", e); } if (!next.equals(first)) { chemicalClassNamesList.add(next); } } } chemicalClassNamesList.add(last); } } List<String> chemicalLigandList = new ArrayList<String>(); List<String> chemicalLigandStartsList = new ArrayList<String>(); if (chemicalLigand != null) { for (ArrayList<String> toto : chemicalLigand) { String first = toto.get(0).trim(); String last = toto.get(1).trim(); // double check first and last order if (first.length() > last.length()) { last = toto.get(0); first = toto.get(1); } else if ((first.length() == last.length()) && (first.compareToIgnoreCase(last) > 0)) { last = toto.get(0); first = toto.get(1); } chemicalLigandStartsList.add(first); if (!last.equals(first)) { String next = first; while (!next.equals(last)) { int ind = next.lastIndexOf("_"); String numb = next.substring(ind + 1, next.length()); try { Integer numbi = Integer.parseInt(numb); next = next.substring(0, ind + 1) + (numbi + 1); } catch (NumberFormatException e) { throw new GrobidException("An exception occured while running Grobid.", e); } if (!next.equals(first)) { chemicalLigandList.add(next); } } } chemicalLigandList.add(last); } } // we need now to map the word id on the actual word flow ChemicalWordsSaxParser parser = new ChemicalWordsSaxParser(); parser.setChemicalAnnotations(chemicalAnnotationsList, chemicalAnnotationsStartsList); parser.setChemicalFormulas(chemicalFormulasList, chemicalFormulasStartsList); parser.setChemicalSubstances(chemicalSubstancesList, chemicalSubstancesStartsList); parser.setChemicalClassNames(chemicalClassNamesList, chemicalClassNamesStartsList); parser.setChemicalLigand(chemicalLigandList, chemicalLigandStartsList); File thefileWords; try { thefileWords = new File(thefile.getParent() + File.separator + thefile.getName().replace(".HC.chemical-names.xml", ".words.xml")); } catch (Exception e) { throw new GrobidException("An exception occured while running Grobid.", e); } List<String> labeled; if (thefileWords != null) { SAXParser p = spf.newSAXParser(); p.parse(thefileWords, parser); labeled = parser.getLabeledResult(); //System.out.println(labeled); // we can now add the features List<OffsetPosition> chemicalTokenPositions = null; List<OffsetPosition> chemicalNamesTokenPositions = null; addFeatures(labeled, writer2, chemicalTokenPositions, chemicalNamesTokenPositions); writer2.write("\n"); } } writer2.close(); } catch (Exception e) { throw new GrobidException("An exception occured while running Grobid.", e); } return totalExamples; } @SuppressWarnings({"UnusedParameters"}) public void addFeatures(List<String> texts, Writer writer, List<OffsetPosition> chemicalTokenPositions, List<OffsetPosition> chemicalNamesTokenPositions) { int totalLine = texts.size(); int posit = 0; boolean isChemicalToken = false; boolean isChemicalNameToken = false; try { for (String line : texts) { FeaturesVectorChemicalEntity featuresVector = FeaturesVectorChemicalEntity.addFeaturesChemicalEntities(line, totalLine, posit, isChemicalToken, isChemicalNameToken); if (featuresVector.label == null) continue; writer.write(featuresVector.printVector()); writer.flush(); posit++; } } catch (Exception e) { throw new GrobidException("An exception occured while running Grobid.", e); } } /** * Command line execution. * * @param args Command line arguments. */ public static void main(String[] args) { Trainer trainer = new ChemicalEntityTrainer(); AbstractTrainer.runTraining(trainer); System.out.println(AbstractTrainer.runEvaluation(trainer)); System.exit(0); } }
20,163
45.568129
112
java