repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/LTFramerConfiguration.h
|
<gh_stars>1-10
//
// LTFramerConfiguration.h
// Pods
//
// Created by <NAME> on 2017. 02. 04..
//
//
#import <Foundation/Foundation.h>
@interface LTFramerConfiguration : NSObject
/**
* Used when layout needs to be flipped horizontally, eg. in Arabic and Hebrew standards
*/
@property (nonatomic, assign, getter = isHorizontallyMirrored) BOOL horizontallyMirrored;
+ (instancetype)sharedConfiguration;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Protocols/LTFramerSizeFittableProtocol.h
|
//
// LTFramerSizeFittable.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
@protocol LTFramerSizeFittable <NSObject>
- (CGSize)sizeThatFits:(CGSize)size;
@end
|
tevelee/LTFramer
|
LTFramer/Convenience/Common/Public/LTFramer_Convenience.h
|
//
// LTFramer.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import "NSObject+LTFramerConvenience.h"
|
tevelee/LTFramer
|
LTFramer/Convenience/iOS/Public/LTFramerKit_Convenience_UIKit.h
|
//
// LTFramer.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import "LTFramer_Convenience.h"
#import "UIView+LTFramerConvenience.h"
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Properties/LTFramerPositionProperty.h
|
//
// LTFramerProperty.h
// Pods
//
// Created by <NAME> on 07/09/16.
//
//
#import "LTFramerProperty.h"
typedef NS_ENUM(NSUInteger, LTFramerPosition) {
LTFramerPositionExact,
LTFramerPositionAlignToLeading,
LTFramerPositionAlignToCenter,
LTFramerPositionAlignToTrailing
};
@interface LTFramerPositionProperty : LTFramerProperty
@property (nonatomic, assign) LTFramerPosition position;
+ (instancetype)propertyWithDirection:(LTFramerDirection)direction position:(LTFramerPosition)position;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/Common/Public/LTFramerStackSubject.h
|
<reponame>tevelee/LTFramer<gh_stars>1-10
//
// LTFramerStackSubject.h
// Pods
//
// Created by <NAME> on 17/09/16.
//
//
#import "LTFramerFrameSettableProtocol.h"
#import "LTFramerSizeFittableProtocol.h"
#import "LTFramerStackElementProtocol.h"
typedef id<LTFramerFrameSettable, LTFramerStackElement, LTFramerSizeFittable> LTFramerStackSubject;
|
tevelee/LTFramer
|
LTFramer/Stack/Common/Public/LTFramerStackAlignment.h
|
//
// LTFramerStackAlignment.h
// Pods
//
// Created by <NAME> on 17/09/16.
//
//
typedef NS_ENUM(NSUInteger, LTFramerStackAlignment) {
LTFramerAlignStretchToFill,
LTFramerAlignLeading,
LTFramerAlignTrailing,
LTFramerAlignCenter,
//LTFramerAlignBaseline is not yet implemented
};
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Protocols/LTFramerFrameGettableProtocol.h
|
<filename>LTFramer/Core/Common/Public/Protocols/LTFramerFrameGettableProtocol.h
//
// LTFramerFrameSettable.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
@protocol LTFramerFrameGettable <NSObject>
- (CGRect)frame;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/iOS/Public/LTFramerKit_Stack_UIKit.h
|
//
// LTFramer.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import "LTFramerKit_Stack.h"
#import "UIView+LTFramerStack.h"
#import "LTFramerStackView.h"
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Protocols/Rules/LTFramerRelativeRuleProtocol.h
|
<reponame>tevelee/LTFramer<gh_stars>1-10
//
// LTFramerRelativeRuleProtocol.h
// Pods
//
// Created by <NAME> on 2016. 10. 11..
//
//
#import "LTFramerRulePriority.h"
#import "LTFramerSubject.h"
@protocol LTFramer;
@protocol LTFramerRelativeRule <NSObject>
@property (nonatomic, nonnull, readonly) id<LTFramer> then;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> equalTo;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> same;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> _Nonnull (^of)(LTFramerSubject _Nonnull subject);
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> left;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> right;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> top;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> bottom;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> width;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> height;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> centerX;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> centerY;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> with;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> the;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> and;
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> _Nonnull (^offset)(double offset);
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> _Nonnull (^multiplier)(double multiplier);
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> _Nonnull (^value)(double value);
@property (nonatomic, nonnull, readonly) id<LTFramerRelativeRule> _Nullable (^priority)(LTFramerRulePriority priority); //Not yet implemented
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Types/LTFramerSubject.h
|
//
// LTFramerSubject.h
// Pods
//
// Created by <NAME> on 25/09/16.
//
//
#import "LTFramerFrameSettableProtocol.h"
typedef id<LTFramerFrameSettable> LTFramerSubject;
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Helpers/NSDictionary+LTFramer.h
|
<gh_stars>1-10
//
// NSDictionary+LTFramer.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
#import <Foundation/Foundation.h>
@interface NSDictionary (LTFramer)
- (NSDictionary*)skyFramer_map:(id(^)(id<NSObject> key, id object))block;
- (NSDictionary*)skyFramer_filter:(BOOL(^)(id<NSObject> key, id object))block;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/iOS/Public/LTFramerStackView.h
|
//
// LTFramerStackView.h
// Pods
//
// Created by <NAME> on 16/09/16.
//
//
#import "LTFramerStack.h"
@interface LTFramerStackView : UIView
@property (nonatomic, strong, readonly) LTFramerStack* stack;
@property (nonatomic, strong) LTFramerStackProperties* properties;
+ (instancetype)stackViewWithViews:(NSArray<UIView*>*)subjects;
- (instancetype)initWithViews:(NSArray<UIView*>*)subjects;
- (void)addArrangedSubview:(UIView *)view;
- (void)removeArrangedSubview:(UIView *)view;
- (void)insertArrangedSubview:(UIView *)view atIndex:(NSUInteger)stackIndex;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Enumerations/LTFramerDirection.h
|
<filename>LTFramer/Core/Common/Public/Enumerations/LTFramerDirection.h
//
// LTFramerDirection.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
typedef NS_ENUM(NSUInteger, LTFramerDirection) {
LTFramerDirectionHorizontal,
LTFramerDirectionVertical
};
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Properties/LTFramerPaddingProperty.h
|
<gh_stars>1-10
//
// LTFramerProperty.h
// Pods
//
// Created by <NAME> on 07/09/16.
//
//
#import "LTFramerProperty.h"
typedef NS_ENUM(NSUInteger, LTFramerPadding) {
LTFramerPaddingLeading,
LTFramerPaddingTrailing
};
@interface LTFramerPaddingProperty : LTFramerProperty
@property (nonatomic, assign) LTFramerPadding padding;
+ (instancetype)propertyWithDirection:(LTFramerDirection)direction padding:(LTFramerPadding)padding;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/Common/Public/LTFramerStackElementProperties.h
|
//
// LTFramerVirtualBox.h
// Pods
//
// Created by <NAME> on 08/09/16.
//
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSUInteger, LTFramerIndividualAlignment) {
LTFramerIndividualAlignmentInherited,
LTFramerIndividualAlignmentStretchToFill,
LTFramerIndividualAlignmentLeading,
LTFramerIndividualAlignmentTrailing,
LTFramerIndividualAlignmentCenter,
//LTFramerIndividualAlignmentBaseline is not yet implemented
};
@interface LTFramerStackElementProperties : NSObject
@property (nonatomic, strong) NSNumber* paddingBefore;
@property (nonatomic, strong) NSNumber* paddingAfter;
@property (nonatomic, strong) NSValue* exactSize;
@property (nonatomic, assign) LTFramerIndividualAlignment alignment;
@property (nonatomic, strong) NSNumber* canGrow;
@property (nonatomic, strong) NSNumber* canShrink;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/LTFramer.h
|
//
// LTFramer.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import <Foundation/Foundation.h>
#import "LTFramerRule.h"
#import "LTFramerFrameSettableProtocol.h"
#import "LTFramerProtocol.h"
@interface LTFramer : NSObject <LTFramer>
+ (_Nonnull instancetype)framerWithSubject:(_Nonnull LTFramerSubject)subject boundingSize:(CGSize)size;
- (void)resetRules;
- (void)addRule:(LTFramerRule* _Nonnull)rule;
- (NSArray<LTFramerRule*>* _Nonnull)allRules;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Rules/LTFramerRelativeRule.h
|
//
// LTFramerRelativeRule.h
// Pods
//
// Created by <NAME> on 06/09/16.
//
//
#import "LTFramerRule.h"
#import "LTFramerSubject.h"
#import "LTFramerProtocol.h"
#import "LTFramerRelativeRuleProtocol.h"
typedef NS_ENUM(NSUInteger, LTFramerRelation) {
LTFramerRelationNone,
LTFramerRelationEquality,
LTFramerRelationLessThan,
LTFramerRelationLessThanOrEqual,
LTFramerRelationGreaterThan,
LTFramerRelationGreaterThanOrEqual
};
typedef NS_ENUM(NSUInteger, LTFramerSupportedProperty) {
LTFramerSupportedPropertyNone,
LTFramerSupportedPropertyLeadingX,
LTFramerSupportedPropertyCenterX,
LTFramerSupportedPropertyTrailingX,
LTFramerSupportedPropertyWidth,
LTFramerSupportedPropertyLeadingY,
LTFramerSupportedPropertyCenterY,
LTFramerSupportedPropertyTrailingY,
LTFramerSupportedPropertyHeight
};
@class LTFramerRelativeRule;
@protocol LTFramerRelativeRuleDelegate <LTFramer>
- (void)relativeRuleDeclarationDidModifyRule:(LTFramerRelativeRule* _Nonnull)rule;
@end
@interface LTFramerRelativeRule : NSObject <LTFramerRelativeRule>
@property (nonatomic, nullable, weak) id<LTFramerRelativeRuleDelegate> delegate;
@property (nonatomic, assign) LTFramerRelation relation;
@property (nonatomic, assign) LTFramerDirection direction;
@property (nonatomic, nullable, weak) LTFramerSubject sourceSubject;
@property (nonatomic, assign) LTFramerSupportedProperty sourceProperty;
@property (nonatomic, assign) LTFramerSupportedProperty targetProperty;
@property (nonatomic, nullable, strong) NSNumber* priorityValue;
@property (nonatomic, nullable, strong) NSNumber* exactValue;
@property (nonatomic, assign) double offsetValue;
@property (nonatomic, assign) double multiplierValue;
+ (instancetype _Nonnull)relativeRuleWithDelegate:(id<LTFramerRelativeRuleDelegate> _Nonnull)delegate;
@end
|
tevelee/LTFramer
|
LTFramer/Convenience/Common/Public/CGRect+LTFramer.h
|
//
// CGRect+LTFramer.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
@import Foundation;
FOUNDATION_EXTERN CGRect CGRectCreate(CGPoint origin, CGSize size);
FOUNDATION_EXTERN CGRect CGRectIntegralMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height);
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Rules/LTFramerRule.h
|
//
// LTFramerRule.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import <Foundation/Foundation.h>
#import "LTFramerSizeProperty.h"
#import "LTFramerPaddingProperty.h"
#import "LTFramerPositionProperty.h"
@interface LTFramerRule : NSObject <NSCopying>
@property (nonatomic, strong) LTFramerProperty* property;
@property (nonatomic, strong) NSNumber* value;
@property (nonatomic, strong) NSNumber* priority;
+ (instancetype)ruleWithDirection:(LTFramerDirection)direction position:(LTFramerPosition)position;
+ (instancetype)ruleWithDirection:(LTFramerDirection)direction exactPosition:(double)position;
+ (instancetype)ruleWithDirection:(LTFramerDirection)direction size:(LTFramerSize)size;
+ (instancetype)ruleWithDirection:(LTFramerDirection)direction exactSize:(double)size;
+ (instancetype)ruleWithDirection:(LTFramerDirection)direction padding:(LTFramerPadding)padding value:(double)value;
- (BOOL)isEqualToRule:(LTFramerRule *)rule;
@end
|
tevelee/LTFramer
|
LTFramer/Convenience/Common/Public/CGPoint+LTFramer.h
|
<reponame>tevelee/LTFramer
//
// CGSize+LTFramer.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
@import Foundation;
FOUNDATION_EXTERN CGPoint CGPointCeil(CGPoint point);
FOUNDATION_EXTERN CGPoint CGPointCeilMake(CGFloat x, CGFloat y);
FOUNDATION_EXTERN CGPoint CGPointFloor(CGPoint point);
FOUNDATION_EXTERN CGPoint CGPointFloorMake(CGFloat x, CGFloat y);
|
tevelee/LTFramer
|
LTFramer/Convenience/Common/Public/CGSize+LTFramer.h
|
//
// CGSize+LTFramer.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
@import Foundation;
#undef CGSizeInfinite
#define CGSizeInfinite CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)
FOUNDATION_EXTERN CGSize CGSizeCeil(CGSize size);
FOUNDATION_EXTERN CGSize CGSizeCeilMake(CGFloat width, CGFloat height);
FOUNDATION_EXTERN CGSize CGSizeFloor(CGSize size);
FOUNDATION_EXTERN CGSize CGSizeFloorMake(CGFloat width, CGFloat height);
|
tevelee/LTFramer
|
LTFramer/Stack/iOS/Public/UIView+LTFramerStack.h
|
//
// UIView+LTFramer_Stack.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
#import "LTFramerStackElementProtocol.h"
@interface UIView (LTFramerStack) <LTFramerStackElement>
@end
|
tevelee/LTFramer
|
LTFramer/Core/iOS/Public/LTFramer+UIKit.h
|
//
// LTFramer+UIView.h
// Pods
//
// Created by <NAME> on 25/09/16.
//
//
#import "LTFramer.h"
@interface LTFramer (UIKit)
+ (instancetype)framerWithView:(UIView*)view;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/Common/Public/Protocols/LTFramerStackElementProtocol.h
|
//
// LTFramerStackElementPropertiesProtocol.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
#import "LTFramerStackElementProperties.h"
@protocol LTFramerStackElement <NSObject>
@property (nonatomic, strong) LTFramerStackElementProperties* stackProperties;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/Common/Public/LTFramerStack.h
|
//
// LTFramerVirtualBox.h
// Pods
//
// Created by <NAME> on 08/09/16.
//
//
#import "LTFramerStackElementProperties.h"
#import "LTFramerStackProperties.h"
#import "LTFramerStackSubject.h"
@interface LTFramerStack : NSObject <LTFramerSizeFittable>
@property (nonatomic, strong) NSArray<LTFramerStackSubject>* subjects;
@property (nonatomic, strong) NSValue* boundingSize;
@property (nonatomic, strong) LTFramerStackProperties* properties;
+ (instancetype)stackWithSubjects:(NSArray<LTFramerStackSubject>*)subjects;
- (void)prepareFrames;
- (CGRect)determineFrameForSubject:(LTFramerStackSubject)subject;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Types/LTFramerRulePriority.h
|
//
// LTFramerRulePriority.h
// Pods
//
// Created by <NAME> on 2016. 10. 11..
//
//
typedef NSInteger LTFramerRulePriority;
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Rules/LTFramerAbsoluteRule.h
|
<filename>LTFramer/Core/Common/Public/Rules/LTFramerAbsoluteRule.h
//
// LTFramerAbsoluteRule.h
// Pods
//
// Created by <NAME> on 2016. 10. 10..
//
//
#import "LTFramerRule.h"
#import "LTFramerProtocol.h"
#import "LTFramerAbsoluteRuleProtocol.h"
@class LTFramerAbsoluteRule;
@protocol LTFramerAbsoluteRuleDelegate <LTFramer>
- (void)absoluteRuleDeclaration:(LTFramerAbsoluteRule* _Nonnull)rule didGenerateNewRule:(LTFramerRule* _Nonnull)rule;
- (void)absoluteRuleDeclaration:(LTFramerAbsoluteRule* _Nonnull)rule didModifyPriority:(LTFramerRulePriority)priority;
@end
@interface LTFramerAbsoluteRule : NSObject <LTFramerAbsoluteRule>
@property (nonatomic, nullable, weak) id<LTFramerAbsoluteRuleDelegate> delegate;
+ (instancetype _Nonnull)absoluteRuleWithDelegate:(id<LTFramerAbsoluteRuleDelegate> _Nonnull)delegate;
@end
|
tevelee/LTFramer
|
LTFramer/Core/iOS/Public/UIView+LTFramer.h
|
<reponame>tevelee/LTFramer<filename>LTFramer/Core/iOS/Public/UIView+LTFramer.h
//
// UIView+LTFramer.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import <UIKit/UIKit.h>
#import "LTFramer.h"
#import "LTFramerFrameInstallableProtocol.h"
#import "LTFramerSizeFittableProtocol.h"
@interface UIView (LTFramer_BlockConvenience) <LTFramerFrameSettable, LTFramerFrameInstallable, LTFramerSizeFittable>
@property (nonatomic, nonnull, readonly) LTFramer* skyFramer;
@end
|
tevelee/LTFramer
|
Example/LTFramer/LTFramerAppDelegate.h
|
<filename>Example/LTFramer/LTFramerAppDelegate.h
//
// LTFramerAppDelegate.h
// LTFramer
//
// Created by <NAME> on 08/21/2016.
// Copyright (c) 2016 <NAME>. All rights reserved.
//
@import UIKit;
@interface LTFramerAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
tevelee/LTFramer
|
LTFramer/Convenience/iOS/Public/UIEdgeInsets+LTFramer.h
|
//
// CGAffineTransform+LTFramer.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
@import UIKit;
FOUNDATION_EXTERN UIEdgeInsets UIEdgeInsetsEqual(CGFloat inset);
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/LTFramerVirtualBox.h
|
//
// LTFramerVirtualBox.h
// Pods
//
// Created by <NAME> on 08/09/16.
//
//
#import "UIView+LTFramer.h"
typedef void(^LTFramerLayoutBlock)(CGRect frame);
@interface LTFramerVirtualBox : NSObject <LTFramerFrameSettable>
@property (nonatomic, assign) CGRect frame;
@property (nonatomic, copy) LTFramerLayoutBlock layout;
+ (instancetype)boxWithLayout:(LTFramerLayoutBlock)layout;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/Common/Private/LTFramerStackElement.h
|
<gh_stars>1-10
//
// LTFramerStackElement.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
#import "LTFramerStackElementProperties.h"
#import "LTFramerSizeFittableProtocol.h"
#import "LTFramerStackSubject.h"
#import "LTFramerStackAlignment.h"
struct LTFramerRange {
double min;
double max;
};
typedef struct LTFramerRange LTFramerRange;
FOUNDATION_EXTERN LTFramerRange LTFramerRangeMake(double min, double max);
@interface LTFramerStackElement : NSObject
@property (nonatomic, strong, readonly) NSString* identifier;
@property (nonatomic, strong) LTFramerStackSubject subject;
@property (nonatomic, assign) LTFramerStackAlignment alignment;
@property (nonatomic, assign) LTFramerRange sizeRange;
@property (nonatomic, assign) NSInteger priority;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Helpers/NSArray+LTFramer.h
|
<filename>LTFramer/Core/Common/Public/Helpers/NSArray+LTFramer.h
//
// NSArray+LTFramer.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import <Foundation/Foundation.h>
@interface NSArray (LTFramerFunctional)
- (NSArray*)skyFramer_map:(id(^)(id object))block;
- (NSArray*)skyFramer_filter:(BOOL(^)(id object))block;
- (NSArray*)skyFramer_while:(BOOL(^)(id object))block;
- (NSArray*)skyFramer_until:(BOOL(^)(id object))block;
- (NSDictionary*)skyFramer_dictionaryUsingKey:(id<NSCopying>(^)(id object))block;
- (id)skyFramer_aggregateWithInitial:(id)initial block:(id(^)(id rolling, id current))block;
- (double)skyFramer_sum:(double(^)(id object))block;
- (double)skyFramer_max:(double(^)(id object))block;
- (double)skyFramer_min:(double(^)(id object))block;
- (BOOL)skyFramer_if:(BOOL(^)(id object))block;
- (id)skyFramer_first:(BOOL(^)(id object))block;
- (void)skyFramer_forEach:(void(^)(id object))block;
@end
|
tevelee/LTFramer
|
LTFramer/Convenience/Common/Public/CGAffineTransform+LTFramer.h
|
<filename>LTFramer/Convenience/Common/Public/CGAffineTransform+LTFramer.h
//
// CGAffineTransform+LTFramer.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
@import Foundation;
FOUNDATION_EXTERN CGAffineTransform CGAffineTransformFromFrameToFrame(CGRect source, CGRect target);
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Protocols/LTFramerFrameInstallableProtocol.h
|
//
// LTFramerFrameInstallable.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
#import "LTFramer.h"
typedef void(^LTFramerBlock)(LTFramer* framer);
@protocol LTFramerFrameInstallable <NSObject>
- (void)installFrame:(LTFramerBlock)block;
- (void)installFrame:(LTFramerBlock)block ignoreTransform:(BOOL)ignoreTransform;
- (void)installFrame:(LTFramerBlock)block inRelativeContainer:(CGRect)rect;
- (void)installFrame:(LTFramerBlock)block ignoreTransform:(BOOL)ignoreTransform inRelativeContainer:(CGRect)rect;
@end
|
tevelee/LTFramer
|
LTFramer/Convenience/iOS/Public/UIView+LTFramerConvenience.h
|
//
// UIView+LTFramer.h
// Pods
//
// Created by <NAME> on 21/08/16.
//
//
#import <UIKit/UIKit.h>
@interface UIView (LTFramer_Convenience)
- (void)addTo:(UIView*)view;
- (CGFloat)skyFramer_minX:(BOOL)ignoreTransform;
- (CGFloat)skyFramer_minY:(BOOL)ignoreTransform;
- (CGFloat)skyFramer_midX:(BOOL)ignoreTransform;
- (CGFloat)skyFramer_midY:(BOOL)ignoreTransform;
- (CGFloat)skyFramer_maxX:(BOOL)ignoreTransform;
- (CGFloat)skyFramer_maxY:(BOOL)ignoreTransform;
- (CGFloat)skyFramer_width:(BOOL)ignoreTransform;
- (CGFloat)skyFramer_height:(BOOL)ignoreTransform;
- (CGPoint)skyFramer_origin:(BOOL)ignoreTransform;
- (CGSize)skyFramer_size:(BOOL)ignoreTransform;
@end
|
tevelee/LTFramer
|
LTFramer/Stack/Common/Public/LTFramerStackProperties.h
|
//
// LTFramerStackProperties.h
// Pods
//
// Created by <NAME> on 16/09/16.
//
//
#import <Foundation/Foundation.h>
#import "LTFramerDirection.h"
#import "LTFramerStackAlignment.h"
typedef NS_ENUM(NSUInteger, LTFramerJustification) {
LTFramerJustifyLeading,
LTFramerJustifyTrailing,
LTFramerJustifyCenter,
LTFramerJustifySpaceBetween,
LTFramerJustifySpaceAround
};
typedef NS_ENUM(NSUInteger, LTFramerOverflowBehaviour) {
LTFramerOverflowBehaviourAllowOverflow,
//LTFramerOverflowBehaviourClipping,
//LTFramerOverflowBehaviourBreakConstraints is not yet implemented
};
@interface LTFramerStackProperties : NSObject
@property (nonatomic, assign) double spacing;
@property (nonatomic, assign) BOOL spacesCanGrow;
@property (nonatomic, assign) BOOL itemsCanGrow;
@property (nonatomic, assign) BOOL itemsCanShrink;
@property (nonatomic, strong) NSValue* itemSize;
@property (nonatomic, assign) LTFramerDirection direction;
@property (nonatomic, assign) LTFramerJustification justification;
@property (nonatomic, assign) LTFramerStackAlignment alignment;
@property (nonatomic, assign) LTFramerOverflowBehaviour overflowBehaviour;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Protocols/Rules/LTFramerAbsoluteRuleProtocol.h
|
//
// LTFramerAbsoluteRuleProtocol.h
// Pods
//
// Created by <NAME> on 2016. 10. 11..
//
//
#import "LTFramerRulePriority.h"
@protocol LTFramer;
@protocol LTFramerAbsoluteRule <NSObject>
@property (nonatomic, nonnull, readonly) id<LTFramer> then;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> and;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> with;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignCenter;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignCenterX;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignCenterY;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignLeft;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignRight;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignTop;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignBottom;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignTopLeft;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignTopRight;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignBottomLeft;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> alignBottomRight;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> fitWidth;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> fitHeight;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> fillWidth;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> fillHeight;
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^width)(double width);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^height)(double height);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^size)(CGSize size);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^left)(double padding);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^right)(double padding);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^top)(double padding);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^bottom)(double padding);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^bothSides)(double padding);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^paddings)(UIEdgeInsets paddings);
@property (nonatomic, nonnull, readonly) id<LTFramerAbsoluteRule> _Nonnull (^priority)(LTFramerRulePriority priority); //Not yet implemented
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Properties/LTFramerProperty.h
|
<reponame>tevelee/LTFramer
//
// LTFramerProperty.h
// Pods
//
// Created by <NAME> on 07/09/16.
//
//
#import "LTFramerDirection.h"
typedef NS_ENUM(NSUInteger, LTFramerConstraint) {
LTFramerConstraintPosition,
LTFramerConstraintSize,
LTFramerConstraintPadding
};
@interface LTFramerProperty : NSObject <NSCopying>
@property (nonatomic, assign) LTFramerDirection direction;
@property (nonatomic, assign) LTFramerConstraint constraint;
+ (instancetype)propertyWithDirection:(LTFramerDirection)direction;
- (BOOL)isEqualToProperty:(LTFramerProperty *)property;
@end
|
tevelee/LTFramer
|
LTFramer/Core/Common/Public/Protocols/LTFramerFrameSettableProtocol.h
|
<reponame>tevelee/LTFramer<gh_stars>1-10
//
// LTFramerFrameSettable.h
// Pods
//
// Created by <NAME> on 15/09/16.
//
//
#import "LTFramerFrameGettableProtocol.h"
@protocol LTFramerFrameSettable <LTFramerFrameGettable>
- (void)setFrame:(CGRect)frame;
@end
|
HectorIdme/Cubo_Rubik
|
rubikCube.h
|
<gh_stars>0
#ifndef RUBIKCUBE_H
#define RUBIKCUBE_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/string_cast.hpp>
#include "shader.h"
#include "std_image.h"
#include "texture.h"
#include <string>
#include <iostream>
#include <queue>
#include <algorithm>
#include <utility>
#include <deque>
#include <vector>
#include <stdlib.h>
#include <fstream>
#define distCub 1.3
using namespace std;
glm::vec3 cubePositions[] = {
glm::vec3(-1.3f, 1.3f, 0.0f),
glm::vec3(0.0f, 1.3f, 0.0f),
glm::vec3(1.3f, 1.3f, 0.0f),
glm::vec3(-1.3f, 0.0f, 0.0f),
glm::vec3(1.3f, 0.0f, 0.0f),
glm::vec3(-1.3f, -1.3f, 0.0f),
glm::vec3(0.0f, -1.3f, 0.0f),
glm::vec3(1.3f, -1.3f, 0.0f),
glm::vec3(-1.3f, 1.3f, 1.3f),
glm::vec3(0.0f, 1.3f, 1.3f),
glm::vec3(1.3f, 1.3f, 1.3f),
glm::vec3(-1.3f, 0.0f, 1.3f),
glm::vec3(0.0f, 0.0f, 1.3f),
glm::vec3(1.3f, 0.0f, 1.3f),
glm::vec3(-1.3f, -1.3f, 1.3f),
glm::vec3(0.0f, -1.3f, 1.3f),
glm::vec3(1.3f, -1.3f, 1.3f),
glm::vec3(-1.3f, 1.3f, -1.3f),
glm::vec3(0.0f, 1.3f, -1.3f),
glm::vec3(1.3f, 1.3f, -1.3f),
glm::vec3(-1.3f, 0.0f, -1.3f),
glm::vec3(0.0f, 0.0f, -1.3f),
glm::vec3(1.3f, 0.0f, -1.3f),
glm::vec3(-1.3f, -1.3f, -1.3f),
glm::vec3(0.0f, -1.3f, -1.3f),
glm::vec3(1.3f, -1.3f, -1.3f),
glm::vec3(0.0f, 0.0f, 0.0f)
};
vector<glm::vec3> cubePositionsH = {
glm::vec3(-distCub, 0.0f, 0.0f),
glm::vec3(0.0f, distCub, 0.0f),
glm::vec3(distCub, 0.0f, 0.0f),
glm::vec3(-distCub, 0.0f, 0.0f),
glm::vec3(distCub, 0.0f, 0.0f),
glm::vec3(-distCub, 0.0f, 0.0f),
glm::vec3(0.0f, -distCub, 0.0f),
glm::vec3(distCub, 0.0f, 0.0f),
glm::vec3(-distCub, 0.0f, distCub),
glm::vec3(0.0f, 0.0f, distCub),
glm::vec3(distCub, 0.0f, distCub),
glm::vec3(-distCub, 0.0f, distCub),
glm::vec3(0.0f, 0.0f, distCub),
glm::vec3(distCub, 0.0f, distCub),
glm::vec3(-distCub, 0.0f, distCub),
glm::vec3(0.0f, 0.0f, distCub),
glm::vec3(distCub, 0.0f, distCub),
glm::vec3(-distCub, 0.0f, -distCub),
glm::vec3(0.0f, 0.0f, -distCub),
glm::vec3(distCub, 0.0f, -distCub),
glm::vec3(-distCub, 0.0f, -distCub),
glm::vec3(0.0f, 0.0f, -distCub),
glm::vec3(distCub, 0.0f, -distCub),
glm::vec3(-distCub, 0.0f, -distCub),
glm::vec3(0.0f, 0.0f, -distCub),
glm::vec3(distCub, 0.0f, -distCub),
glm::vec3(0.0f, 0.0f, 0.0f)
};
vector<glm::vec3> cubePositionsV = {
glm::vec3(0.0f, distCub, 0.0f),
glm::vec3(0.0f, distCub, 0.0f),
glm::vec3(0.0f, distCub, 0.0f),
glm::vec3(-distCub, 0.0f, 0.0f),
glm::vec3(distCub, 0.0f, 0.0f),
glm::vec3(0.0f, -distCub, 0.0f),
glm::vec3(0.0f, -distCub, 0.0f),
glm::vec3(0.0f, -distCub, 0.0f),
glm::vec3(0.0f, distCub, distCub),
glm::vec3(0.0f, distCub, distCub),
glm::vec3(0.0f, distCub, distCub),
glm::vec3(0.0f, 0.0f, distCub),
glm::vec3(0.0f, 0.0f, distCub),
glm::vec3(0.0f, 0.0f, distCub),
glm::vec3(0.0f, -distCub, distCub),
glm::vec3(0.0f, -distCub, distCub),
glm::vec3(0.0f, -distCub, distCub),
glm::vec3(0.0f, distCub, -distCub),
glm::vec3(0.0f, distCub, -distCub),
glm::vec3(0.0f, distCub, -distCub),
glm::vec3(0.0f, 0.0f, -distCub),
glm::vec3(0.0f, 0.0f, -distCub),
glm::vec3(0.0f, 0.0f, -distCub),
glm::vec3(0.0f, -distCub, -distCub),
glm::vec3(0.0f, -distCub, -distCub),
glm::vec3(0.0f, -distCub, -distCub),
glm::vec3(0.0f, 0.0f, 0.0f)
};
vector<glm::vec3> cubePositionsV2 = {
glm::vec3(-distCub, distCub, 0.0f),
glm::vec3(0.0f, distCub, 0.0f),
glm::vec3(distCub, distCub, 0.0f),
glm::vec3(-distCub, 0.0f, 0.0f),
glm::vec3(distCub, 0.0f, 0.0f),
glm::vec3(-distCub, -distCub, 0.0f),
glm::vec3(0.0f, -distCub, 0.0f),
glm::vec3(distCub, -distCub, 0.0f),
glm::vec3(-distCub, distCub, 0.0f),
glm::vec3(0.0f, distCub, 0.0f),
glm::vec3(distCub, distCub, 0.0f),
glm::vec3(-distCub, 0.0f, 0.0f),
glm::vec3(0.0f, 0.0f, distCub),
glm::vec3(distCub, 0.0f, 0.0f),
glm::vec3(-distCub, -distCub, 0.0f),
glm::vec3(0.0f, -distCub, 0.0f),
glm::vec3(distCub, -distCub, 0.0f),
glm::vec3(-distCub, distCub, 0.0f),
glm::vec3(0.0f, distCub, 0.0f),
glm::vec3(distCub, distCub, 0.0f),
glm::vec3(-distCub, 0.0f, 0.0f),
glm::vec3(0.0f, 0.0f, -distCub),
glm::vec3(distCub, 0.0f, 0.0f),
glm::vec3(-distCub, -distCub, 0.0f),
glm::vec3(0.0f, -distCub, 0.0f),
glm::vec3(distCub, -distCub, 0.0f),
glm::vec3(0.0f, 0.0f, 0.0f)
};
struct NodeCube {
///COLORS
////orange(izq/0) - green(frente/1) - white(arriba/2) - blue(atras/3)
///- yellow(abajo/4) - red(der/5) - black(hidden/6)
vector<vector<float>> cors = {
{1,0.552,0.121}, {0,0.678,0.019},{1,1,1},
{ 0.003,0.266,0.756 }, {0.960,0.843,0} , {1, 0.078, 0.133},{0,0,0}
};
vector<unsigned int> text_ref;
glm::mat4 model = glm::mat4(1.0f);
glm::mat4 model_text = glm::mat4(1.0f);
glm::vec3 cubePosition;
vector<unsigned int> cube_textures; //ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA
vector<vector<float>> colors; //ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA
int ID;
void setPos(glm::vec3 pos) {
cubePosition = pos;
model = glm::translate(model, cubePosition);
}
void setModel(glm::mat4 model_) {
model = model_;
}
void setModelText(glm::mat4 model_) {
model_text = model_;
}
glm::mat4 getModel() {
return model;
}
void setTex(vector<unsigned int> text) {
cube_textures = text;
}
void setTexRef(vector<unsigned int> text) {
text_ref = text;
}
void setColor(vector<vector<float>> cor) {
colors = cor;
}
void setID(int id) {
ID = id;
}
char getCorCara_(int cara) {
char cor='-';
if (cara == 0) {
if (colors[0] == cors[0]) cor = 'o';
else if (colors[0] == cors[1]) cor = 'g';
else if (colors[0] == cors[2]) cor = 'w';
else if (colors[0] == cors[3]) cor = 'l';
else if (colors[0] == cors[4]) cor = 'y';
else if (colors[0] == cors[5]) cor = 'r';
else if (colors[0] == cors[6]) cor = '-';
}
else if (cara == 1) {
if (colors[1] == cors[0]) cor = 'o';
else if (colors[1] == cors[1]) cor = 'g';
else if (colors[1] == cors[2]) cor = 'w';
else if (colors[1] == cors[3]) cor = 'l';
else if (colors[1] == cors[4]) cor = 'y';
else if (colors[1] == cors[5]) cor = 'r';
else if (colors[1] == cors[6]) cor = '-';
}
else if (cara == 2) {
if (colors[2] == cors[0]) cor = 'o';
else if (colors[2] == cors[1]) cor = 'g';
else if (colors[2] == cors[2]) cor = 'w';
else if (colors[2] == cors[3]) cor = 'l';
else if (colors[2] == cors[4]) cor = 'y';
else if (colors[2] == cors[5]) cor = 'r';
else if (colors[2] == cors[6]) cor = '-';
}
else if (cara == 3) {
if (colors[3] == cors[0]) cor = 'o';
else if (colors[3] == cors[1]) cor = 'g';
else if (colors[3] == cors[2]) cor = 'w';
else if (colors[3] == cors[3]) cor = 'l';
else if (colors[3] == cors[4]) cor = 'y';
else if (colors[3] == cors[5]) cor = 'r';
else if (colors[3] == cors[6]) cor = '-';
}
else if (cara == 4) {
if (colors[4] == cors[0]) cor = 'o';
else if (colors[4] == cors[1]) cor = 'g';
else if (colors[4] == cors[2]) cor = 'w';
else if (colors[4] == cors[3]) cor = 'l';
else if (colors[4] == cors[4]) cor = 'y';
else if (colors[4] == cors[5]) cor = 'r';
else if (colors[4] == cors[6]) cor = '-';
}
else if (cara == 5) {
if (colors[5] == cors[0]) cor = 'o';
else if (colors[5] == cors[1]) cor = 'g';
else if (colors[5] == cors[2]) cor = 'w';
else if (colors[5] == cors[3]) cor = 'l';
else if (colors[5] == cors[4]) cor = 'y';
else if (colors[5] == cors[5]) cor = 'r';
else if (colors[5] == cors[6]) cor = '-';
}
return cor;
}
///
bool searchText(unsigned int text,int textura_cara) {
//letra U
if (textura_cara == 0) {
for (int i = 0; i < 9; i++)
if (text == text_ref[i]) return true;
}
//letra C1
else if (textura_cara == 1) {
for (int i = 9; i < 18; i++)
if (text == text_ref[i]) return true;
}
//letra S
else if (textura_cara ==2) {
for (int i = 18; i < 27; i++)
if (text == text_ref[i]) return true;
}
//letra P
else if (textura_cara == 3) {
for (int i = 27; i < 36; i++)
if (text == text_ref[i]) return true;
}
//letra C2
else if (textura_cara == 4) {
for (int i = 36; i < 45; i++)
if (text == text_ref[i]) return true;
}
//letra G
else if (textura_cara == 5) {
for (int i = 45; i < 55; i++)
if (text == text_ref[i]) return true;
}
return false;
}
char getCorCara(int cara) {
char cor = '-';
if (cara == 0) {
if (searchText(cube_textures[0], 3)) cor = 'o';
else if (searchText(cube_textures[0], 0)) cor = 'g';
else if (searchText(cube_textures[0], 2)) cor = 'w';
else if (searchText(cube_textures[0], 5)) cor = 'l';
else if (searchText(cube_textures[0], 4)) cor = 'y';
else if (searchText(cube_textures[0], 1)) cor = 'r';
else cor = '-';
}
else if (cara == 1) {
if (searchText(cube_textures[1], 3)) cor = 'o';
else if (searchText(cube_textures[1], 0)) cor = 'g';
else if (searchText(cube_textures[1], 2)) cor = 'w';
else if (searchText(cube_textures[1], 5)) cor = 'l';
else if (searchText(cube_textures[1], 4)) cor = 'y';
else if (searchText(cube_textures[1], 1)) cor = 'r';
else cor = '-';
}
else if (cara == 2) {
if (searchText(cube_textures[2], 3)) cor = 'o';
else if (searchText(cube_textures[2], 0)) cor = 'g';
else if (searchText(cube_textures[2], 2)) cor = 'w';
else if (searchText(cube_textures[2], 5)) cor = 'l';
else if (searchText(cube_textures[2], 4)) cor = 'y';
else if (searchText(cube_textures[2], 1)) cor = 'r';
else cor = '-';
}
else if (cara == 3) {
if (searchText(cube_textures[3], 3)) cor = 'o';
else if (searchText(cube_textures[3], 0)) cor = 'g';
else if (searchText(cube_textures[3], 2)) cor = 'w';
else if (searchText(cube_textures[3], 5)) cor = 'l';
else if (searchText(cube_textures[3], 4)) cor = 'y';
else if (searchText(cube_textures[3], 1)) cor = 'r';
else cor = '-';
}
else if (cara == 4) {
if (searchText(cube_textures[4], 3)) cor = 'o';
else if (searchText(cube_textures[4], 0)) cor = 'g';
else if (searchText(cube_textures[4], 2)) cor = 'w';
else if (searchText(cube_textures[4], 5)) cor = 'l';
else if (searchText(cube_textures[4], 4)) cor = 'y';
else if (searchText(cube_textures[4], 1)) cor = 'r';
else cor = '-';
}
else if (cara == 5) {
if (searchText(cube_textures[5], 3)) cor = 'o';
else if (searchText(cube_textures[5], 0)) cor = 'g';
else if (searchText(cube_textures[5], 2)) cor = 'w';
else if (searchText(cube_textures[5], 5)) cor = 'l';
else if (searchText(cube_textures[5], 4)) cor = 'y';
else if (searchText(cube_textures[5], 1)) cor = 'r';
else cor = '-';
}
return cor;
}
glm::mat4 getModelMatrix(bool op = 0) {
if (op)return model;
else return glm::translate(model, cubePosition);
}
glm::mat4 getModelText() {
return model_text;
}
void drawCubeText() {
for (int i = 0; i < 6; i++) {
glBindTexture(GL_TEXTURE_2D, cube_textures[i]);
glDrawArrays(GL_TRIANGLES, i*6, 6);
}
}
void drawCubeColors(Shader shaderc) {
for (int i = 0; i < 6; i++) {
shaderc.setVec3("ourColor", colors[i][0], colors[i][1], colors[i][2]);
glDrawArrays(GL_TRIANGLES, i * 6, 6);
}
}
};
struct Camada {
vector<NodeCube> cubos;
vector<glm::vec3> cubePos;
glm::mat4 model_center = glm::mat4(1.0f);
glm::mat4 model_camada = glm::mat4(1.0f);
glm::mat4 model_text_ref = glm::mat4(1.0f);
int ID;
int orientation;
bool animation = 0;
float ang_ = 0;
bool girar = 0;
float speed = 0.25;
void setID(int id) {
ID = id;
}
void setCamada(vector<NodeCube> grupo) {
cubos = grupo;
}
void setCubePos(vector<glm::vec3> cubePos_) {
cubePos = cubePos_;
}
void setOr(int or ) {
orientation = or;
if (orientation == 1) cubePos = cubePositionsV;
else if (orientation == 2) cubePos = cubePositionsV2;
else cubePos = cubePositionsH;
getPos_Center();
}
void getPos_Center() {
if (ID == 0) model_center = glm::translate(model_center, cubePos[1]);
else if(ID == 1) model_center = glm::translate(model_center, cubePos[26]);
else if (ID == 2) model_center = glm::translate(model_center, cubePos[6]);
else if (ID == 3) model_center = glm::translate(model_center, cubePos[3]);
else if (ID == 4) model_center = glm::translate(model_center, cubePos[26]);
else if (ID == 5) model_center = glm::translate(model_center, cubePos[4]);
else if (ID == 6) model_center = glm::translate(model_center, cubePos[12]);
else if (ID == 7) model_center = glm::translate(model_center, cubePos[26]);
else if (ID == 8) model_center = glm::translate(model_center, cubePos[21]);
}
void printPos() {
cout << "\nCamada " << ID << " orientation " << orientation << "\n";
for (int i = 0; i < cubePos.size(); i++) {
cout << i << " " << to_string(this->cubePos[i]) << "\n";
}cout << "\n";
}
void set_cubes_rot(bool rotation) {
glm::vec3 direction;
glm::vec3 direction_;
if (animation) {
if (orientation == 0) {
if (rotation) {
direction = glm::vec3(0.0f, 1.0f, 0.0f);
direction_ = glm::vec3(0.0f, -1.0f, 0.0f);
}
else {
direction = glm::vec3(0.0f, -1.0f, 0.0f);
direction_ = glm::vec3(0.0f, 1.0f, 0.0f);
}
}
else if(orientation == 1){
if (rotation) {
direction = glm::vec3(1.0f, 0.0f, 0.0f);
direction_ = glm::vec3(-1.0f, 0.0f, 0.0f);
}
else {
direction = glm::vec3(-1.0f, 0.0f, 0.0f);
direction_ = glm::vec3(1.0f, 0.0f, 0.0f);
}
}
else if (orientation == 2) {
if (!rotation) {
direction = glm::vec3(0.0f, 0.0f, 1.0f);
direction_ = glm::vec3(0.0f, 0.0f, -1.0f);
}
else {
direction = glm::vec3(0.0f, 0.0f, -1.0f);
direction_ = glm::vec3(0.0f, 0.0f, 1.0f);
}
}
if (girar) {
model_center = glm::rotate(model_center, (float)(glm::radians(speed)), direction);
model_text_ref = glm::rotate(model_text_ref, (float)(glm::radians(speed)), direction_);
ang_ += speed;
}
model_camada = model_center;
cubos[4].setModel(model_center);
cubos[4].setModelText(model_text_ref);
}
}
};
struct RubikCube {
vector<char> stateCube;
vector<int> camada_mas_complet;
NodeCube cubos[27];
Camada camadas[9];
string sol_movs;
bool flag_sol = 0;
bool borr;
string m;
///COLORS
////orange(izq/0) - green(frente/1) - white(arriba/2) - blue(atras/3)
///- yellow(abajo/4) - red(der/5) - black(hidden/6)
vector<vector<float>> colors = {
{1,0.552,0.121}, {0,0.678,0.019},{1,1,1},
{ 0.003,0.266,0.756 }, {0.960,0.843,0} , {1, 0.078, 0.133},{0,0,0}
};
vector<unsigned int> texturas;
vector<unsigned int> texturas_colors;
void fileStateCube() {
ofstream myFile("stateCub.dat");
for (int i = 0; i < stateCube.size(); i++) {
myFile << stateCube[i] << " ";
if ((i + 1) % 9 == 0) myFile << "\n";
}
myFile.close();
}
RubikCube(vector<unsigned int> text) {
texturas = text;
//CREANDO CUBOS
//COLORS
/*
for (int i = 0; i < 27; i++) {
cubos[i].setPos(cubePositions[i]);
cubos[i].setID(i);
switch (i) { //ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA
////PRIMERA FILA 1
case 0:
cubos[0].setColor({ colors[6],colors[6],colors[0],colors[6],colors[6],colors[2] });
break;
case 1:
cubos[1].setColor({ colors[6],colors[6],colors[6],colors[6],colors[6],colors[2] });
break;
case 2:
cubos[2].setColor({ colors[6],colors[6],colors[6],colors[5],colors[6],colors[2] });
break;
////SEGUNDA FILA 1
case 3:
cubos[3].setColor({ colors[6],colors[6],colors[0],colors[6],colors[6],colors[6] });
break;
case 4:
cubos[4].setColor({ colors[6],colors[6],colors[6],colors[5],colors[6],colors[6] });
break;
////TERCERA FILA 1
case 5:
cubos[5].setColor({ colors[6],colors[6],colors[0],colors[6],colors[4],colors[6] });
break;
case 6:
cubos[6].setColor({ colors[6],colors[6],colors[6],colors[6],colors[4],colors[6] });
break;
case 7:
cubos[7].setColor({ colors[6],colors[6],colors[6],colors[5],colors[4],colors[6] });
break;
////PRIMERA FILA 0
case 8:
cubos[8].setColor({ colors[6],colors[1],colors[0],colors[6],colors[6],colors[2] });
break;
case 9:
cubos[9].setColor({ colors[6],colors[1],colors[6],colors[6],colors[6],colors[2] });
break;
case 10:
cubos[10].setColor({ colors[6],colors[1],colors[6],colors[5],colors[6],colors[2] });
break;
////SEGUNDA FILA 0
case 11:
cubos[11].setColor({ colors[6],colors[1],colors[0],colors[6],colors[6],colors[6] });
break;
case 12:
cubos[12].setColor({ colors[6],colors[1],colors[6],colors[6],colors[6],colors[6] });
break;
case 13:
cubos[13].setColor({ colors[6],colors[1],colors[6],colors[5],colors[6],colors[6] });
break;
////TERCERA FILA 0
case 14:
cubos[14].setColor({ colors[6],colors[1],colors[0],colors[6],colors[4],colors[6] });
break;
case 15:
cubos[15].setColor({ colors[6],colors[1],colors[6],colors[6],colors[4],colors[6] });
break;
case 16:
cubos[16].setColor({ colors[6],colors[1],colors[6],colors[5],colors[4],colors[6] });
break;
////PRIMERA FILA 2
case 17:
cubos[17].setColor({ colors[3],colors[6],colors[0],colors[6],colors[6],colors[2] });
break;
case 18:
cubos[18].setColor({ colors[3],colors[6],colors[6],colors[6],colors[6],colors[2] });
break;
case 19:
cubos[19].setColor({ colors[3],colors[6],colors[6],colors[5],colors[6],colors[2] });
break;
////SEGUNDA FILA 2
case 20:
cubos[20].setColor({ colors[3],colors[6],colors[0],colors[6],colors[6],colors[6] });
break;
case 21:
cubos[21].setColor({ colors[3],colors[6],colors[6],colors[6],colors[6],colors[6] });
break;
case 22:
cubos[22].setColor({ colors[3],colors[6],colors[6],colors[5],colors[6],colors[6] });
break;
////TERCERA FILA 2
case 23:
cubos[23].setColor({ colors[3],colors[6],colors[0],colors[6],colors[4],colors[6] });
break;
case 24:
cubos[24].setColor({ colors[3],colors[6],colors[6],colors[6],colors[4],colors[6] });
break;
case 25:
cubos[25].setColor({ colors[3],colors[6],colors[6],colors[5],colors[4],colors[6] });
break;
}
}
*/
//TEXTURES
for (int i = 0; i < 27; i++) {
cubos[i].setPos(cubePositions[i]);
cubos[i].setID(i);
cubos[i].setTexRef(texturas);
switch (i) { //ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA
////PRIMERA FILA 1
case 0:
cubos[0].setTex({ texturas[54],texturas[54],texturas[28],texturas[54],texturas[54],texturas[21] });
break;
case 1:
cubos[1].setTex({ texturas[54],texturas[54],texturas[54],texturas[54],texturas[54],texturas[22] });
break;
case 2:
cubos[2].setTex({ texturas[54],texturas[54],texturas[54],texturas[10],texturas[54],texturas[23] });
break;
////SEGUNDA FILA 1
case 3:
cubos[3].setTex({ texturas[54],texturas[54],texturas[31],texturas[54],texturas[54],texturas[54] });
break;
case 4:
cubos[4].setTex({ texturas[54],texturas[54],texturas[54],texturas[13],texturas[54],texturas[54] });
break;
////TERCERA FILA 1
case 5:
cubos[5].setTex({ texturas[54],texturas[54],texturas[34],texturas[54],texturas[39],texturas[54] });
break;
case 6:
cubos[6].setTex({ texturas[54],texturas[54],texturas[54],texturas[54],texturas[40],texturas[54] });
break;
case 7:
cubos[7].setTex({ texturas[54],texturas[54],texturas[54],texturas[16],texturas[41],texturas[54] });
break;
////PRIMERA FILA 0
case 8:
cubos[8].setTex({ texturas[54],texturas[0],texturas[29],texturas[54],texturas[54],texturas[24] });
break;
case 9:
cubos[9].setTex({ texturas[54],texturas[1],texturas[54],texturas[54],texturas[54],texturas[25] });
break;
case 10:
cubos[10].setTex({ texturas[54],texturas[2],texturas[54],texturas[9],texturas[54],texturas[26] });
break;
////SEGUNDA FILA 0
case 11:
cubos[11].setTex({ texturas[54],texturas[3],texturas[32],texturas[54],texturas[54],texturas[54] });
break;
case 12:
cubos[12].setTex({ texturas[54],texturas[4],texturas[54],texturas[54],texturas[54],texturas[54] });
break;
case 13:
cubos[13].setTex({ texturas[54],texturas[5],texturas[54],texturas[12],texturas[54],texturas[54] });
break;
////TERCERA FILA 0
case 14:
cubos[14].setTex({ texturas[54],texturas[6],texturas[35],texturas[54],texturas[42],texturas[54] });
break;
case 15:
cubos[15].setTex({ texturas[54],texturas[7],texturas[54],texturas[54],texturas[43],texturas[54] });
break;
case 16:
cubos[16].setTex({ texturas[54],texturas[8],texturas[54],texturas[15],texturas[44],texturas[54] });
break;
////PRIMERA FILA 2
case 17:
cubos[17].setTex({ texturas[47],texturas[54],texturas[27],texturas[54],texturas[54],texturas[18] });
break;
case 18:
cubos[18].setTex({ texturas[46],texturas[54],texturas[54],texturas[54],texturas[54],texturas[19] });
break;
case 19:
cubos[19].setTex({ texturas[45],texturas[54],texturas[54],texturas[11],texturas[54],texturas[20] });
break;
////SEGUNDA FILA 2
case 20:
cubos[20].setTex({ texturas[50],texturas[54],texturas[30],texturas[54],texturas[54],texturas[54] });
break;
case 21:
cubos[21].setTex({ texturas[49],texturas[54],texturas[54],texturas[54],texturas[54],texturas[54] });
break;
case 22:
cubos[22].setTex({ texturas[48],texturas[54],texturas[54],texturas[14],texturas[54],texturas[54] });
break;
////TERCERA FILA 2
case 23:
cubos[23].setTex({ texturas[53],texturas[54],texturas[33],texturas[54],texturas[36],texturas[54] });
break;
case 24:
cubos[24].setTex({ texturas[52],texturas[54],texturas[54],texturas[54],texturas[37],texturas[54] });
break;
case 25:
cubos[25].setTex({ texturas[51],texturas[54],texturas[54],texturas[17],texturas[38],texturas[54] });
break;
}
}
//CREANDO CAMADAS
camadas[0].setID(0);
camadas[0].setOr(0);
camadas[0].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[0],cubos[1], cubos[2],
cubos[8],cubos[9], cubos[10] });
camadas[1].setID(1);
camadas[1].setOr(0);
camadas[1].setCamada({ cubos[20],cubos[21], cubos[22],
cubos[3],cubos[26],cubos[4],
cubos[11],cubos[12], cubos[13]});
camadas[2].setID(2);
camadas[2].setOr(0);
camadas[2].setCamada({ cubos[23],cubos[24], cubos[25],
cubos[5],cubos[6], cubos[7],
cubos[14],cubos[15], cubos[16] });
camadas[3].setID(3);
camadas[3].setOr(1);
camadas[3].setCamada({ cubos[17], cubos[0],cubos[8],
cubos[20],cubos[3], cubos[11],
cubos[23],cubos[5],cubos[14] });
camadas[4].setID(4);
camadas[4].setOr(1);
camadas[4].setCamada({ cubos[18],cubos[1], cubos[9],
cubos[21],cubos[26],cubos[12],
cubos[24],cubos[6], cubos[15] });
camadas[5].setID(5);
camadas[5].setOr(1);
camadas[5].setCamada({ cubos[19],cubos[2], cubos[10],
cubos[22],cubos[4], cubos[13],
cubos[25],cubos[7], cubos[16] });
camadas[6].setID(6);
camadas[6].setOr(2);
camadas[6].setCamada({ cubos[8], cubos[9],cubos[10],
cubos[11],cubos[12], cubos[13],
cubos[14],cubos[15],cubos[16] });
camadas[7].setID(7);
camadas[7].setOr(2);
camadas[7].setCamada({ cubos[0],cubos[1], cubos[2],
cubos[3],cubos[26],cubos[4],
cubos[5],cubos[6], cubos[7] });
camadas[8].setID(8);
camadas[8].setOr(2);
camadas[8].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[20],cubos[21], cubos[22],
cubos[23],cubos[24], cubos[25] });
//ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA (colores)
//
//CAMADAS PARA SOLVER: ARRIBA - IZQ - FRENTE - DER - ATRAS - ABAJO
//ARRIBA
for (int i = 0; i <9; i++) stateCube.push_back(camadas[0].cubos[i].getCorCara(5));
//IZQ
for (int i = 0; i <9; i++) stateCube.push_back(camadas[3].cubos[i].getCorCara(2));
//FRENTE
for (int i = 0; i < 9; i++) stateCube.push_back(camadas[6].cubos[i].getCorCara(1));
//DER
stateCube.push_back(camadas[5].cubos[2].getCorCara(3));
stateCube.push_back(camadas[5].cubos[1].getCorCara(3));
stateCube.push_back(camadas[5].cubos[0].getCorCara(3));
stateCube.push_back(camadas[5].cubos[5].getCorCara(3));
stateCube.push_back(camadas[5].cubos[4].getCorCara(3));
stateCube.push_back(camadas[5].cubos[3].getCorCara(3));
stateCube.push_back(camadas[5].cubos[8].getCorCara(3));
stateCube.push_back(camadas[5].cubos[7].getCorCara(3));
stateCube.push_back(camadas[5].cubos[6].getCorCara(3));
//ATRAS
stateCube.push_back(camadas[8].cubos[2].getCorCara(0));
stateCube.push_back(camadas[8].cubos[1].getCorCara(0));
stateCube.push_back(camadas[8].cubos[0].getCorCara(0));
stateCube.push_back(camadas[8].cubos[5].getCorCara(0));
stateCube.push_back(camadas[8].cubos[4].getCorCara(0));
stateCube.push_back(camadas[8].cubos[3].getCorCara(0));
stateCube.push_back(camadas[8].cubos[8].getCorCara(0));
stateCube.push_back(camadas[8].cubos[7].getCorCara(0));
stateCube.push_back(camadas[8].cubos[6].getCorCara(0));
//ABAJO
stateCube.push_back(camadas[2].cubos[6].getCorCara(4));
stateCube.push_back(camadas[2].cubos[7].getCorCara(4));
stateCube.push_back(camadas[2].cubos[8].getCorCara(4));
stateCube.push_back(camadas[2].cubos[3].getCorCara(4));
stateCube.push_back(camadas[2].cubos[4].getCorCara(4));
stateCube.push_back(camadas[2].cubos[5].getCorCara(4));
stateCube.push_back(camadas[2].cubos[0].getCorCara(4));
stateCube.push_back(camadas[2].cubos[1].getCorCara(4));
stateCube.push_back(camadas[2].cubos[2].getCorCara(4));
cout << "Estado Cubo\n";
for (int i = 0; i < stateCube.size(); i++) {
cout << stateCube[i] << " ";
if ((i + 1) % 9 == 0) cout << "\n";
}cout << "\n";
fileStateCube();
}
NodeCube getCube(int id) {
for (int i = 0; i < 27; i++) {
if (cubos[i].ID == id) return cubos[i];
}
}
void setTexturasCors(vector<unsigned int> textCor) {
texturas_colors = textCor;
}
void changeTextures() {
//TEXTURES
for (int i = 0; i < 27; i++) {
cubos[i].setTexRef(texturas_colors);
switch (i) { //ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA
////PRIMERA FILA 1
case 0:
cubos[0].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[28],texturas_colors[54],texturas_colors[54],texturas_colors[21] });
break;
case 1:
cubos[1].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[22] });
break;
case 2:
cubos[2].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[10],texturas_colors[54],texturas_colors[23] });
break;
////SEGUNDA FILA 1
case 3:
cubos[3].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[31],texturas_colors[54],texturas_colors[54],texturas_colors[54] });
break;
case 4:
cubos[4].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[13],texturas_colors[54],texturas_colors[54] });
break;
////TERCERA FILA 1
case 5:
cubos[5].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[34],texturas_colors[54],texturas_colors[39],texturas_colors[54] });
break;
case 6:
cubos[6].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[40],texturas_colors[54] });
break;
case 7:
cubos[7].setTex({ texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[16],texturas_colors[41],texturas_colors[54] });
break;
////PRIMERA FILA 0
case 8:
cubos[8].setTex({ texturas_colors[54],texturas_colors[0],texturas_colors[29],texturas_colors[54],texturas_colors[54],texturas_colors[24] });
break;
case 9:
cubos[9].setTex({ texturas_colors[54],texturas_colors[1],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[25] });
break;
case 10:
cubos[10].setTex({ texturas_colors[54],texturas_colors[2],texturas_colors[54],texturas_colors[9],texturas_colors[54],texturas_colors[26] });
break;
////SEGUNDA FILA 0
case 11:
cubos[11].setTex({ texturas_colors[54],texturas_colors[3],texturas_colors[32],texturas_colors[54],texturas_colors[54],texturas_colors[54] });
break;
case 12:
cubos[12].setTex({ texturas_colors[54],texturas_colors[4],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[54] });
break;
case 13:
cubos[13].setTex({ texturas_colors[54],texturas_colors[5],texturas_colors[54],texturas_colors[12],texturas_colors[54],texturas_colors[54] });
break;
////TERCERA FILA 0
case 14:
cubos[14].setTex({ texturas_colors[54],texturas_colors[6],texturas_colors[35],texturas_colors[54],texturas_colors[42],texturas_colors[54] });
break;
case 15:
cubos[15].setTex({ texturas_colors[54],texturas_colors[7],texturas_colors[54],texturas_colors[54],texturas_colors[43],texturas_colors[54] });
break;
case 16:
cubos[16].setTex({ texturas_colors[54],texturas_colors[8],texturas_colors[54],texturas_colors[15],texturas_colors[44],texturas_colors[54] });
break;
////PRIMERA FILA 2
case 17:
cubos[17].setTex({ texturas_colors[47],texturas_colors[54],texturas_colors[27],texturas_colors[54],texturas_colors[54],texturas_colors[18] });
break;
case 18:
cubos[18].setTex({ texturas_colors[46],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[19] });
break;
case 19:
cubos[19].setTex({ texturas_colors[45],texturas_colors[54],texturas_colors[54],texturas_colors[11],texturas_colors[54],texturas_colors[20] });
break;
////SEGUNDA FILA 2
case 20:
cubos[20].setTex({ texturas_colors[50],texturas_colors[54],texturas_colors[30],texturas_colors[54],texturas_colors[54],texturas_colors[54] });
break;
case 21:
cubos[21].setTex({ texturas_colors[49],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[54] });
break;
case 22:
cubos[22].setTex({ texturas_colors[48],texturas_colors[54],texturas_colors[54],texturas_colors[14],texturas_colors[54],texturas_colors[54] });
break;
////TERCERA FILA 2
case 23:
cubos[23].setTex({ texturas_colors[53],texturas_colors[54],texturas_colors[33],texturas_colors[54],texturas_colors[36],texturas_colors[54] });
break;
case 24:
cubos[24].setTex({ texturas_colors[52],texturas_colors[54],texturas_colors[54],texturas_colors[54],texturas_colors[37],texturas_colors[54] });
break;
case 25:
cubos[25].setTex({ texturas_colors[51],texturas_colors[54],texturas_colors[54],texturas_colors[17],texturas_colors[38],texturas_colors[54] });
break;
}
}
//CREANDO CAMADAS
camadas[0].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[0],cubos[1], cubos[2],
cubos[8],cubos[9], cubos[10] });
camadas[1].setCamada({ cubos[20],cubos[21], cubos[22],
cubos[3],cubos[26],cubos[4],
cubos[11],cubos[12], cubos[13] });
camadas[2].setCamada({ cubos[23],cubos[24], cubos[25],
cubos[5],cubos[6], cubos[7],
cubos[14],cubos[15], cubos[16] });
camadas[3].setCamada({ cubos[17], cubos[0],cubos[8],
cubos[20],cubos[3], cubos[11],
cubos[23],cubos[5],cubos[14] });
camadas[4].setCamada({ cubos[18],cubos[1], cubos[9],
cubos[21],cubos[26],cubos[12],
cubos[24],cubos[6], cubos[15] });
camadas[5].setCamada({ cubos[19],cubos[2], cubos[10],
cubos[22],cubos[4], cubos[13],
cubos[25],cubos[7], cubos[16] });
camadas[6].setCamada({ cubos[8], cubos[9],cubos[10],
cubos[11],cubos[12], cubos[13],
cubos[14],cubos[15],cubos[16] });
camadas[7].setCamada({ cubos[0],cubos[1], cubos[2],
cubos[3],cubos[26],cubos[4],
cubos[5],cubos[6], cubos[7] });
camadas[8].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[20],cubos[21], cubos[22],
cubos[23],cubos[24], cubos[25] });
//ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA (colores)
//CAMADAS PARA SOLVER: ARRIBA - IZQ - FRENTE - DER - ATRAS - ABAJO
//ARRIBA
for (int i = 0; i < 9; i++) stateCube.push_back(camadas[0].cubos[i].getCorCara(5));
//IZQ
for (int i = 0; i < 9; i++) stateCube.push_back(camadas[3].cubos[i].getCorCara(2));
//FRENTE
for (int i = 0; i < 9; i++) stateCube.push_back(camadas[6].cubos[i].getCorCara(1));
//DER
stateCube.push_back(camadas[5].cubos[2].getCorCara(3));
stateCube.push_back(camadas[5].cubos[1].getCorCara(3));
stateCube.push_back(camadas[5].cubos[0].getCorCara(3));
stateCube.push_back(camadas[5].cubos[5].getCorCara(3));
stateCube.push_back(camadas[5].cubos[4].getCorCara(3));
stateCube.push_back(camadas[5].cubos[3].getCorCara(3));
stateCube.push_back(camadas[5].cubos[8].getCorCara(3));
stateCube.push_back(camadas[5].cubos[7].getCorCara(3));
stateCube.push_back(camadas[5].cubos[6].getCorCara(3));
//ATRAS
stateCube.push_back(camadas[8].cubos[2].getCorCara(0));
stateCube.push_back(camadas[8].cubos[1].getCorCara(0));
stateCube.push_back(camadas[8].cubos[0].getCorCara(0));
stateCube.push_back(camadas[8].cubos[5].getCorCara(0));
stateCube.push_back(camadas[8].cubos[4].getCorCara(0));
stateCube.push_back(camadas[8].cubos[3].getCorCara(0));
stateCube.push_back(camadas[8].cubos[8].getCorCara(0));
stateCube.push_back(camadas[8].cubos[7].getCorCara(0));
stateCube.push_back(camadas[8].cubos[6].getCorCara(0));
//ABAJO
stateCube.push_back(camadas[2].cubos[6].getCorCara(4));
stateCube.push_back(camadas[2].cubos[7].getCorCara(4));
stateCube.push_back(camadas[2].cubos[8].getCorCara(4));
stateCube.push_back(camadas[2].cubos[3].getCorCara(4));
stateCube.push_back(camadas[2].cubos[4].getCorCara(4));
stateCube.push_back(camadas[2].cubos[5].getCorCara(4));
stateCube.push_back(camadas[2].cubos[0].getCorCara(4));
stateCube.push_back(camadas[2].cubos[1].getCorCara(4));
stateCube.push_back(camadas[2].cubos[2].getCorCara(4));
fileStateCube();
}
int getCamadaMasCompleta() {
int no_cor = 0;
//ARRIBA
for (int i = 0; i < 9; i++)
if (camadas[0].cubos[i].getCorCara(5) != 'w') no_cor++;
camada_mas_complet.push_back(no_cor);
no_cor = 0;
//IZQ
for (int i = 0; i < 9; i++)
if (camadas[3].cubos[i].getCorCara(2) != 'o') no_cor++;
camada_mas_complet.push_back(no_cor);
no_cor = 0;
//FRENTE
for (int i = 0; i < 9; i++)
if (camadas[6].cubos[i].getCorCara(1) != 'g') no_cor++;
camada_mas_complet.push_back(no_cor);
no_cor = 0;
//DER
if (camadas[5].cubos[2].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[1].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[0].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[5].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[4].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[3].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[8].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[7].getCorCara(3) != 'r') no_cor++;
if (camadas[5].cubos[6].getCorCara(3) != 'r') no_cor++;
camada_mas_complet.push_back(no_cor);
no_cor = 0;
//ATRAS
if (camadas[8].cubos[2].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[1].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[0].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[5].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[4].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[3].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[8].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[7].getCorCara(0) != 'l') no_cor++;
if (camadas[8].cubos[6].getCorCara(0) != 'l') no_cor++;
camada_mas_complet.push_back(no_cor);
no_cor = 0;
//ABAJO
if (camadas[2].cubos[6].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[7].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[8].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[3].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[4].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[5].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[0].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[1].getCorCara(4) != 'y') no_cor++;
if (camadas[2].cubos[2].getCorCara(4) != 'y') no_cor++;
camada_mas_complet.push_back(no_cor);
no_cor = 0;
pair<int, int> mini = { camada_mas_complet[0],0};
for (int i = 0; i < camada_mas_complet.size(); i++) {
if (camada_mas_complet[i] < mini.first) {
mini = { camada_mas_complet[i] ,i};
}
}
camada_mas_complet.clear();
return mini.second;
}
void updateStateCubo(Camada camadas[9]) {
stateCube.clear();
//CAMADAS PARA SOLVER: ARRIBA - IZQ - FRENTE - DER - ATRAS - ABAJO
//ARRIBA
for (int i = 0; i < 9; i++) stateCube.push_back(camadas[0].cubos[i].getCorCara(5));
//IZQ
for (int i = 0; i < 9; i++) stateCube.push_back(camadas[3].cubos[i].getCorCara(2));
//FRENTE
for (int i = 0; i < 9; i++) stateCube.push_back(camadas[6].cubos[i].getCorCara(1));
//DER
stateCube.push_back(camadas[5].cubos[2].getCorCara(3));
stateCube.push_back(camadas[5].cubos[1].getCorCara(3));
stateCube.push_back(camadas[5].cubos[0].getCorCara(3));
stateCube.push_back(camadas[5].cubos[5].getCorCara(3));
stateCube.push_back(camadas[5].cubos[4].getCorCara(3));
stateCube.push_back(camadas[5].cubos[3].getCorCara(3));
stateCube.push_back(camadas[5].cubos[8].getCorCara(3));
stateCube.push_back(camadas[5].cubos[7].getCorCara(3));
stateCube.push_back(camadas[5].cubos[6].getCorCara(3));
//ATRAS
stateCube.push_back(camadas[8].cubos[2].getCorCara(0));
stateCube.push_back(camadas[8].cubos[1].getCorCara(0));
stateCube.push_back(camadas[8].cubos[0].getCorCara(0));
stateCube.push_back(camadas[8].cubos[5].getCorCara(0));
stateCube.push_back(camadas[8].cubos[4].getCorCara(0));
stateCube.push_back(camadas[8].cubos[3].getCorCara(0));
stateCube.push_back(camadas[8].cubos[8].getCorCara(0));
stateCube.push_back(camadas[8].cubos[7].getCorCara(0));
stateCube.push_back(camadas[8].cubos[6].getCorCara(0));
//ABAJO
stateCube.push_back(camadas[2].cubos[6].getCorCara(4));
stateCube.push_back(camadas[2].cubos[7].getCorCara(4));
stateCube.push_back(camadas[2].cubos[8].getCorCara(4));
stateCube.push_back(camadas[2].cubos[3].getCorCara(4));
stateCube.push_back(camadas[2].cubos[4].getCorCara(4));
stateCube.push_back(camadas[2].cubos[5].getCorCara(4));
stateCube.push_back(camadas[2].cubos[0].getCorCara(4));
stateCube.push_back(camadas[2].cubos[1].getCorCara(4));
stateCube.push_back(camadas[2].cubos[2].getCorCara(4));
fileStateCube();
}
//UPDATE COLORS HORIZONTAL
void updateCh(vector<vector<float>>& a) {
vector<vector<float>> b;
queue<vector<float>> q;
q.push(a[0]);
b.push_back(a[3]);
q.push(a[1]);
b.push_back(a[2]);
b.push_back(q.front());
q.pop();
b.push_back(q.front());
q.pop();
b.push_back(a[4]);
b.push_back(a[5]);
a.clear();
a = b;
}
void updateChA(vector<vector<float>>& a) {
vector<vector<float>> b;
deque<vector<float>> q;
q.push_back(a[0]);
b.push_back(a[2]);
q.push_back(a[1]);
b.push_back(a[3]);
b.push_back(q.back());
q.pop_back();
b.push_back(q.back());
q.pop_back();
b.push_back(a[4]);
b.push_back(a[5]);
a.clear();
a = b;
}
//UPDATE COLORS VERTICAL
void updateCh2(vector<vector<float>>& a) {
vector<vector<float>> b;
deque<vector<float>> q;
q.push_back(a[0]);
b.push_back(a[4]);
q.push_back(a[1]);
b.push_back(a[5]);
b.push_back(a[2]);
b.push_back(a[3]);
b.push_back(q.back());
q.pop_back();
b.push_back(q.back());
q.pop_back();
a.clear();
a = b;
}
void updateCh2A(vector<vector<float>>& a) {
vector<vector<float>> b;
queue<vector<float>> q;
q.push(a[0]);
b.push_back(a[5]);
q.push(a[1]);
b.push_back(a[4]);
b.push_back(a[2]);
b.push_back(a[3]);
b.push_back(q.front());
q.pop();
b.push_back(q.front());
q.pop();
a.clear();
a = b;
}
//UPDATE COLORS VERTICAL-HORIZONTAL
void updateCh3(vector<vector<float>>& a) {
vector<vector<float>> b;
deque<vector<float>> q;
b.push_back(a[0]);
b.push_back(a[1]);
q.push_back(a[2]);
b.push_back(a[4]);
q.push_back(a[3]);
b.push_back(a[5]);
b.push_back(q.back());
q.pop_back();
b.push_back(q.back());
q.pop_back();
a.clear();
a = b;
}
void updateCh3A(vector<vector<float>>& a) {
vector<vector<float>> b;
queue<vector<float>> q;
b.push_back(a[0]);
b.push_back(a[1]);
q.push(a[2]);
b.push_back(a[5]);
q.push(a[3]);
b.push_back(a[4]);
b.push_back(q.front());
q.pop();
b.push_back(q.front());
q.pop();
a.clear();
a = b;
}
void changeCubes(NodeCube &cubOrigen, vector<vector<float>> cubRefCor, bool cor ,int or, bool rot) {
cubOrigen.model = glm::mat4(1.0f);
cubOrigen.model = glm::translate(cubOrigen.model, cubOrigen.cubePosition);
if (cor) {
if (or == 0) {
if(rot) updateCh(cubRefCor);
else updateChA(cubRefCor);
}
else if (or == 1) {
if (rot) updateCh2(cubRefCor);
else updateCh2A(cubRefCor);
}
else if (or == 2) {
if (rot) updateCh3(cubRefCor);
else updateCh3A(cubRefCor);
}
cubOrigen.colors = cubRefCor;
}
}
void updatefinalCamadas_Cors(int idx,int or, bool rotation) {
///punto de modificacion y estado
vector<NodeCube> tmp;
if (or == 0) {
if (rotation) {
tmp.push_back(camadas[idx].cubos[2]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[6]);
}
else {
tmp.push_back(camadas[idx].cubos[6]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[2]);
}
}
else if (or == 1) {
if (rotation) {
tmp.push_back(camadas[idx].cubos[6]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[2]);
}
else {
tmp.push_back(camadas[idx].cubos[2]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[6]);
}
}
else if (or == 2) {
if (rotation) {
tmp.push_back(camadas[idx].cubos[6]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[2]);
}
else {
tmp.push_back(camadas[idx].cubos[2]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[6]);
}
}
///CAMADA HORIZONTAL
if (idx == 0) {
changeCubes(cubos[8], tmp[6].colors,1,0, rotation);
changeCubes(cubos[9], tmp[7].colors, 1, 0, rotation);
changeCubes(cubos[10], tmp[8].colors, 1, 0, rotation);
changeCubes(cubos[0], tmp[3].colors, 1, 0, rotation);
changeCubes(cubos[1], tmp[4].colors, 1, 0, rotation);
changeCubes(cubos[2], tmp[5].colors, 1, 0, rotation);
changeCubes(cubos[17], tmp[0].colors, 1, 0, rotation);
changeCubes(cubos[18], tmp[1].colors, 1, 0, rotation);
changeCubes(cubos[19], tmp[2].colors, 1, 0, rotation);
}
else if (idx == 1) {
changeCubes(cubos[11], tmp[6].colors, 1, 0, rotation);
changeCubes(cubos[12], tmp[7].colors, 1, 0, rotation);
changeCubes(cubos[13], tmp[8].colors, 1, 0, rotation);
changeCubes(cubos[3], tmp[3].colors, 1, 0, rotation);
changeCubes(cubos[26], tmp[4].colors,0,0, rotation);
changeCubes(cubos[4], tmp[5].colors, 1, 0, rotation);
changeCubes(cubos[20], tmp[0].colors, 1, 0, rotation);
changeCubes(cubos[21], tmp[1].colors, 1, 0, rotation);
changeCubes(cubos[22], tmp[2].colors, 1, 0, rotation);
}
else if (idx == 2) {
changeCubes(cubos[14], tmp[6].colors, 1, 0, rotation);
changeCubes(cubos[15], tmp[7].colors, 1, 0, rotation);
changeCubes(cubos[16], tmp[8].colors, 1, 0, rotation);
changeCubes(cubos[5], tmp[3].colors, 1, 0, rotation);
changeCubes(cubos[6], tmp[4].colors, 1, 0, rotation);
changeCubes(cubos[7], tmp[5].colors, 1, 0, rotation);
changeCubes(cubos[23], tmp[0].colors, 1, 0, rotation);
changeCubes(cubos[24], tmp[1].colors, 1, 0, rotation);
changeCubes(cubos[25], tmp[2].colors, 1, 0, rotation);
}
///CAMADA VERTICAL
else if (idx == 3) {
changeCubes(cubos[23], tmp[6].colors, 1, 1, rotation);
changeCubes(cubos[5], tmp[7].colors, 1, 1, rotation);
changeCubes(cubos[14], tmp[8].colors, 1, 1, rotation);
changeCubes(cubos[20], tmp[3].colors, 1, 1, rotation);
changeCubes(cubos[3], tmp[4].colors, 1, 1, rotation);
changeCubes(cubos[11], tmp[5].colors, 1, 1, rotation);
changeCubes(cubos[17], tmp[0].colors, 1, 1, rotation);
changeCubes(cubos[0], tmp[1].colors, 1, 1, rotation);
changeCubes(cubos[8], tmp[2].colors, 1, 1, rotation);
}
else if (idx == 4) {
changeCubes(cubos[9], tmp[2].colors, 1, 1, rotation);
changeCubes(cubos[12], tmp[5].colors, 1, 1, rotation);
changeCubes(cubos[15], tmp[8].colors, 1, 1, rotation);
changeCubes(cubos[1], tmp[1].colors, 1, 1, rotation);
changeCubes(cubos[26], tmp[4].colors,0,1, rotation);
changeCubes(cubos[6], tmp[7].colors, 1, 1, rotation);
changeCubes(cubos[18], tmp[0].colors, 1, 1, rotation);
changeCubes(cubos[21], tmp[3].colors, 1, 1, rotation);
changeCubes(cubos[24], tmp[6].colors, 1, 1, rotation);
}
else if (idx == 5) {
changeCubes(cubos[10], tmp[2].colors, 1, 1, rotation);
changeCubes(cubos[13], tmp[5].colors, 1, 1, rotation);
changeCubes(cubos[16], tmp[8].colors, 1, 1, rotation);
changeCubes(cubos[2], tmp[1].colors, 1, 1, rotation);
changeCubes(cubos[4], tmp[4].colors, 1, 1, rotation);
changeCubes(cubos[7], tmp[7].colors, 1, 1, rotation);
changeCubes(cubos[19], tmp[0].colors, 1, 1, rotation);
changeCubes(cubos[22], tmp[3].colors, 1, 1, rotation);
changeCubes(cubos[25], tmp[6].colors, 1, 1, rotation);
}
///CAMADA VERTICAL-HORIZONTAL
else if (idx == 6) {
changeCubes(cubos[10], tmp[2].colors, 1, 2, rotation);
changeCubes(cubos[13], tmp[5].colors, 1, 2, rotation);
changeCubes(cubos[16], tmp[8].colors, 1, 2, rotation);
changeCubes(cubos[9], tmp[1].colors, 1, 2, rotation);
changeCubes(cubos[12], tmp[4].colors, 1, 2, rotation);
changeCubes(cubos[15], tmp[7].colors, 1, 2, rotation);
changeCubes(cubos[8], tmp[0].colors, 1, 2, rotation);
changeCubes(cubos[11], tmp[3].colors, 1, 2, rotation);
changeCubes(cubos[14], tmp[6].colors, 1, 2, rotation);
}
else if (idx == 7) {
changeCubes(cubos[2], tmp[2].colors, 1, 2, rotation);
changeCubes(cubos[4], tmp[5].colors, 1, 2, rotation);
changeCubes(cubos[7], tmp[8].colors, 1, 2, rotation);
changeCubes(cubos[1], tmp[1].colors, 1, 2, rotation);
changeCubes(cubos[26], tmp[4].colors,0,2, rotation);
changeCubes(cubos[6], tmp[7].colors, 1, 2, rotation);
changeCubes(cubos[0], tmp[0].colors, 1, 2, rotation);
changeCubes(cubos[3], tmp[3].colors, 1, 2, rotation);
changeCubes(cubos[5], tmp[6].colors, 1, 2, rotation);
}
else if (idx == 8) {
changeCubes(cubos[19], tmp[2].colors, 1, 2, rotation);
changeCubes(cubos[22], tmp[5].colors, 1, 2, rotation);
changeCubes(cubos[25], tmp[8].colors, 1, 2, rotation);
changeCubes(cubos[18], tmp[1].colors, 1, 2, rotation);
changeCubes(cubos[21], tmp[4].colors, 1, 2, rotation);
changeCubes(cubos[24], tmp[7].colors, 1, 2, rotation);
changeCubes(cubos[17], tmp[0].colors, 1, 2, rotation);
changeCubes(cubos[20], tmp[3].colors, 1, 2, rotation);
changeCubes(cubos[23], tmp[6].colors, 1, 2, rotation);
}
//////////////////
//actualizando camadas
camadas[0].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[0],cubos[1], cubos[2],
cubos[8],cubos[9], cubos[10] });
camadas[1].setCamada({ cubos[20],cubos[21], cubos[22],
cubos[3],cubos[26],cubos[4],
cubos[11],cubos[12], cubos[13] });
camadas[2].setCamada({ cubos[23],cubos[24], cubos[25],
cubos[5],cubos[6], cubos[7],
cubos[14],cubos[15], cubos[16] });
camadas[3].setCamada({ cubos[17], cubos[0],cubos[8],
cubos[20],cubos[3], cubos[11],
cubos[23],cubos[5],cubos[14] });
camadas[4].setCamada({ cubos[18],cubos[1], cubos[9],
cubos[21],cubos[26],cubos[12],
cubos[24],cubos[6], cubos[15] });
camadas[5].setCamada({ cubos[19],cubos[2], cubos[10],
cubos[22],cubos[4], cubos[13],
cubos[25],cubos[7], cubos[16] });
camadas[6].setCamada({ cubos[8], cubos[9],cubos[10],
cubos[11],cubos[12], cubos[13],
cubos[14],cubos[15],cubos[16] });
camadas[7].setCamada({ cubos[0],cubos[1], cubos[2],
cubos[3],cubos[26],cubos[4],
cubos[5],cubos[6], cubos[7] });
camadas[8].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[20],cubos[21], cubos[22],
cubos[23],cubos[24], cubos[25] });
//ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA
updateStateCubo(camadas);
}
//UPDATE TEXTURES HORIZONTAL
void updateCh(vector<unsigned int>& a) {
vector<unsigned int> b;
queue<unsigned int> q;
q.push(a[0]);
b.push_back(a[3]);
q.push(a[1]);
b.push_back(a[2]);
b.push_back(q.front());
q.pop();
b.push_back(q.front());
q.pop();
b.push_back(a[4]);
b.push_back(a[5]);
a.clear();
a = b;
}
void updateChA(vector<unsigned int>& a) {
vector<unsigned int> b;
deque<unsigned int> q;
q.push_back(a[0]);
b.push_back(a[2]);
q.push_back(a[1]);
b.push_back(a[3]);
b.push_back(q.back());
q.pop_back();
b.push_back(q.back());
q.pop_back();
b.push_back(a[4]);
b.push_back(a[5]);
a.clear();
a = b;
}
//UPDATE TEXTURES VERTICAL
void updateCh2(vector<unsigned int>& a) {
vector<unsigned int> b;
deque<unsigned int> q;
q.push_back(a[0]);
b.push_back(a[4]);
q.push_back(a[1]);
b.push_back(a[5]);
b.push_back(a[2]);
b.push_back(a[3]);
b.push_back(q.back());
q.pop_back();
b.push_back(q.back());
q.pop_back();
a.clear();
a = b;
}
void updateCh2A(vector<unsigned int>& a) {
vector<unsigned int> b;
queue<unsigned int> q;
q.push(a[0]);
b.push_back(a[5]);
q.push(a[1]);
b.push_back(a[4]);
b.push_back(a[2]);
b.push_back(a[3]);
b.push_back(q.front());
q.pop();
b.push_back(q.front());
q.pop();
a.clear();
a = b;
}
//UPDATE TEXTURES VERTICAL-HORIZONTAL
void updateCh3(vector<unsigned int>& a) {
vector<unsigned int> b;
deque<unsigned int> q;
b.push_back(a[0]);
b.push_back(a[1]);
q.push_back(a[2]);
b.push_back(a[4]);
q.push_back(a[3]);
b.push_back(a[5]);
b.push_back(q.back());
q.pop_back();
b.push_back(q.back());
q.pop_back();
a.clear();
a = b;
}
void updateCh3A(vector<unsigned int>& a) {
vector<unsigned int> b;
queue<unsigned int> q;
b.push_back(a[0]);
b.push_back(a[1]);
q.push(a[2]);
b.push_back(a[5]);
q.push(a[3]);
b.push_back(a[4]);
b.push_back(q.front());
q.pop();
b.push_back(q.front());
q.pop();
a.clear();
a = b;
}
void changeCubes(NodeCube& cubOrigen, vector<unsigned int> cubRefCor, bool cor, int or , bool rot) {
cubOrigen.model = glm::mat4(1.0f);
cubOrigen.model = glm::translate(cubOrigen.model, cubOrigen.cubePosition);
if (cor) {
if (or == 0) {
if (rot) updateCh(cubRefCor);
else updateChA(cubRefCor);
}
else if (or == 1) {
if (rot) updateCh2(cubRefCor);
else updateCh2A(cubRefCor);
}
else if (or == 2) {
if (rot) updateCh3(cubRefCor);
else updateCh3A(cubRefCor);
}
cubOrigen.cube_textures = cubRefCor;
}
}
void updatefinalCamadas(int idx, int or , bool rotation, int& mov_cam) {
///punto de modificacion y estado
vector<NodeCube> tmp;
if (or == 0) {
if (rotation) {
tmp.push_back(camadas[idx].cubos[2]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[6]);
}
else {
tmp.push_back(camadas[idx].cubos[6]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[2]);
}
}
else if (or == 1) {
if (rotation) {
tmp.push_back(camadas[idx].cubos[6]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[2]);
}
else {
tmp.push_back(camadas[idx].cubos[2]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[6]);
}
}
else if (or == 2) {
if (rotation) {
tmp.push_back(camadas[idx].cubos[6]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[2]);
}
else {
tmp.push_back(camadas[idx].cubos[2]);
tmp.push_back(camadas[idx].cubos[5]);
tmp.push_back(camadas[idx].cubos[8]);
tmp.push_back(camadas[idx].cubos[1]);
tmp.push_back(camadas[idx].cubos[4]);
tmp.push_back(camadas[idx].cubos[7]);
tmp.push_back(camadas[idx].cubos[0]);
tmp.push_back(camadas[idx].cubos[3]);
tmp.push_back(camadas[idx].cubos[6]);
}
}
///CAMADA HORIZONTAL
if (idx == 0) {
changeCubes(cubos[8], tmp[6].cube_textures, 1, 0, rotation);
changeCubes(cubos[9], tmp[7].cube_textures, 1, 0, rotation);
changeCubes(cubos[10], tmp[8].cube_textures, 1, 0, rotation);
changeCubes(cubos[0], tmp[3].cube_textures, 1, 0, rotation);
changeCubes(cubos[1], tmp[4].cube_textures, 1, 0, rotation);
changeCubes(cubos[2], tmp[5].cube_textures, 1, 0, rotation);
changeCubes(cubos[17], tmp[0].cube_textures, 1, 0, rotation);
changeCubes(cubos[18], tmp[1].cube_textures, 1, 0, rotation);
changeCubes(cubos[19], tmp[2].cube_textures, 1, 0, rotation);
}
else if (idx == 1) {
changeCubes(cubos[11], tmp[6].cube_textures, 1, 0, rotation);
changeCubes(cubos[12], tmp[7].cube_textures, 1, 0, rotation);
changeCubes(cubos[13], tmp[8].cube_textures, 1, 0, rotation);
changeCubes(cubos[3], tmp[3].cube_textures, 1, 0, rotation);
changeCubes(cubos[26], tmp[4].cube_textures, 0, 0, rotation);
changeCubes(cubos[4], tmp[5].cube_textures, 1, 0, rotation);
changeCubes(cubos[20], tmp[0].cube_textures, 1, 0, rotation);
changeCubes(cubos[21], tmp[1].cube_textures, 1, 0, rotation);
changeCubes(cubos[22], tmp[2].cube_textures, 1, 0, rotation);
}
else if (idx == 2) {
changeCubes(cubos[14], tmp[6].cube_textures, 1, 0, rotation);
changeCubes(cubos[15], tmp[7].cube_textures, 1, 0, rotation);
changeCubes(cubos[16], tmp[8].cube_textures, 1, 0, rotation);
changeCubes(cubos[5], tmp[3].cube_textures, 1, 0, rotation);
changeCubes(cubos[6], tmp[4].cube_textures, 1, 0, rotation);
changeCubes(cubos[7], tmp[5].cube_textures, 1, 0, rotation);
changeCubes(cubos[23], tmp[0].cube_textures, 1, 0, rotation);
changeCubes(cubos[24], tmp[1].cube_textures, 1, 0, rotation);
changeCubes(cubos[25], tmp[2].cube_textures, 1, 0, rotation);
}
///CAMADA VERTICAL
else if (idx == 3) {
changeCubes(cubos[23], tmp[6].cube_textures, 1, 1, rotation);
changeCubes(cubos[5], tmp[7].cube_textures, 1, 1, rotation);
changeCubes(cubos[14], tmp[8].cube_textures, 1, 1, rotation);
changeCubes(cubos[20], tmp[3].cube_textures, 1, 1, rotation);
changeCubes(cubos[3], tmp[4].cube_textures, 1, 1, rotation);
changeCubes(cubos[11], tmp[5].cube_textures, 1, 1, rotation);
changeCubes(cubos[17], tmp[0].cube_textures, 1, 1, rotation);
changeCubes(cubos[0], tmp[1].cube_textures, 1, 1, rotation);
changeCubes(cubos[8], tmp[2].cube_textures, 1, 1, rotation);
}
else if (idx == 4) {
changeCubes(cubos[9], tmp[2].cube_textures, 1, 1, rotation);
changeCubes(cubos[12], tmp[5].cube_textures, 1, 1, rotation);
changeCubes(cubos[15], tmp[8].cube_textures, 1, 1, rotation);
changeCubes(cubos[1], tmp[1].cube_textures, 1, 1, rotation);
changeCubes(cubos[26], tmp[4].cube_textures, 0, 1, rotation);
changeCubes(cubos[6], tmp[7].cube_textures, 1, 1, rotation);
changeCubes(cubos[18], tmp[0].cube_textures, 1, 1, rotation);
changeCubes(cubos[21], tmp[3].cube_textures, 1, 1, rotation);
changeCubes(cubos[24], tmp[6].cube_textures, 1, 1, rotation);
}
else if (idx == 5) {
changeCubes(cubos[10], tmp[2].cube_textures, 1, 1, rotation);
changeCubes(cubos[13], tmp[5].cube_textures, 1, 1, rotation);
changeCubes(cubos[16], tmp[8].cube_textures, 1, 1, rotation);
changeCubes(cubos[2], tmp[1].cube_textures, 1, 1, rotation);
changeCubes(cubos[4], tmp[4].cube_textures, 1, 1, rotation);
changeCubes(cubos[7], tmp[7].cube_textures, 1, 1, rotation);
changeCubes(cubos[19], tmp[0].cube_textures, 1, 1, rotation);
changeCubes(cubos[22], tmp[3].cube_textures, 1, 1, rotation);
changeCubes(cubos[25], tmp[6].cube_textures, 1, 1, rotation);
}
///CAMADA VERTICAL-HORIZONTAL
else if (idx == 6) {
changeCubes(cubos[10], tmp[2].cube_textures, 1, 2, rotation);
changeCubes(cubos[13], tmp[5].cube_textures, 1, 2, rotation);
changeCubes(cubos[16], tmp[8].cube_textures, 1, 2, rotation);
changeCubes(cubos[9], tmp[1].cube_textures, 1, 2, rotation);
changeCubes(cubos[12], tmp[4].cube_textures, 1, 2, rotation);
changeCubes(cubos[15], tmp[7].cube_textures, 1, 2, rotation);
changeCubes(cubos[8], tmp[0].cube_textures, 1, 2, rotation);
changeCubes(cubos[11], tmp[3].cube_textures, 1, 2, rotation);
changeCubes(cubos[14], tmp[6].cube_textures, 1, 2, rotation);
cubos[10].model_text = camadas[idx].model_text_ref;
cubos[13].model_text = camadas[idx].model_text_ref;
cubos[16].model_text = camadas[idx].model_text_ref;
cubos[9].model_text = camadas[idx].model_text_ref;
cubos[12].model_text = camadas[idx].model_text_ref;
cubos[15].model_text = camadas[idx].model_text_ref;
cubos[8].model_text = camadas[idx].model_text_ref;
cubos[11].model_text = camadas[idx].model_text_ref;
cubos[14].model_text = camadas[idx].model_text_ref;
}
else if (idx == 7) {
changeCubes(cubos[2], tmp[2].cube_textures, 1, 2, rotation);
changeCubes(cubos[4], tmp[5].cube_textures, 1, 2, rotation);
changeCubes(cubos[7], tmp[8].cube_textures, 1, 2, rotation);
changeCubes(cubos[1], tmp[1].cube_textures, 1, 2, rotation);
changeCubes(cubos[26], tmp[4].cube_textures, 0, 2, rotation);
changeCubes(cubos[6], tmp[7].cube_textures, 1, 2, rotation);
changeCubes(cubos[0], tmp[0].cube_textures, 1, 2, rotation);
changeCubes(cubos[3], tmp[3].cube_textures, 1, 2, rotation);
changeCubes(cubos[5], tmp[6].cube_textures, 1, 2, rotation);
}
else if (idx == 8) {
changeCubes(cubos[19], tmp[2].cube_textures, 1, 2, rotation);
changeCubes(cubos[22], tmp[5].cube_textures, 1, 2, rotation);
changeCubes(cubos[25], tmp[8].cube_textures, 1, 2, rotation);
changeCubes(cubos[18], tmp[1].cube_textures, 1, 2, rotation);
changeCubes(cubos[21], tmp[4].cube_textures, 1, 2, rotation);
changeCubes(cubos[24], tmp[7].cube_textures, 1, 2, rotation);
changeCubes(cubos[17], tmp[0].cube_textures, 1, 2, rotation);
changeCubes(cubos[20], tmp[3].cube_textures, 1, 2, rotation);
changeCubes(cubos[23], tmp[6].cube_textures, 1, 2, rotation);
/*
cubos[19].model_text = camadas[idx].model_text_ref;
cubos[22].model_text = camadas[idx].model_text_ref;
cubos[25].model_text = camadas[idx].model_text_ref;
cubos[18].model_text = camadas[idx].model_text_ref;
cubos[21].model_text = camadas[idx].model_text_ref;
cubos[24].model_text = camadas[idx].model_text_ref;
cubos[17].model_text = camadas[idx].model_text_ref;
cubos[20].model_text = camadas[idx].model_text_ref;
cubos[23].model_text = camadas[idx].model_text_ref;
*/
}
//////////////////
//actualizando camadas
camadas[0].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[0],cubos[1], cubos[2],
cubos[8],cubos[9], cubos[10] });
camadas[1].setCamada({ cubos[20],cubos[21], cubos[22],
cubos[3],cubos[26],cubos[4],
cubos[11],cubos[12], cubos[13] });
camadas[2].setCamada({ cubos[23],cubos[24], cubos[25],
cubos[5],cubos[6], cubos[7],
cubos[14],cubos[15], cubos[16] });
camadas[3].setCamada({ cubos[17], cubos[0],cubos[8],
cubos[20],cubos[3], cubos[11],
cubos[23],cubos[5],cubos[14] });
camadas[4].setCamada({ cubos[18],cubos[1], cubos[9],
cubos[21],cubos[26],cubos[12],
cubos[24],cubos[6], cubos[15] });
camadas[5].setCamada({ cubos[19],cubos[2], cubos[10],
cubos[22],cubos[4], cubos[13],
cubos[25],cubos[7], cubos[16] });
camadas[6].setCamada({ cubos[8], cubos[9],cubos[10],
cubos[11],cubos[12], cubos[13],
cubos[14],cubos[15],cubos[16] });
camadas[7].setCamada({ cubos[0],cubos[1], cubos[2],
cubos[3],cubos[26],cubos[4],
cubos[5],cubos[6], cubos[7] });
camadas[8].setCamada({ cubos[17],cubos[18], cubos[19],
cubos[20],cubos[21], cubos[22],
cubos[23],cubos[24], cubos[25] });
//ATRAS - FRENTE - IZQ - DER - ABAJO - ARRIBA
updateStateCubo(camadas);
mov_cam = getCamadaMasCompleta();
//cout << "Camada mas completa: " << mov_cam << endl;
}
void updateCamadas(int idx) {
if (camadas[idx].animation){
if (idx == 0) {
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[0]);
camadas[0].cubos[3].setModel(camadas[0].model_camada);
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[2]);
camadas[0].cubos[5].setModel(camadas[0].model_camada);
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[8]);
camadas[0].cubos[6].setModel(camadas[0].model_camada);
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[9]);
camadas[0].cubos[7].setModel(camadas[0].model_camada);
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[10]);
camadas[0].cubos[8].setModel(camadas[0].model_camada);
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[17]);
camadas[0].cubos[0].setModel(camadas[0].model_camada);
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[18]);
camadas[0].cubos[1].setModel(camadas[0].model_camada);
camadas[0].model_camada = camadas[0].model_center;
camadas[0].model_camada = glm::translate(camadas[0].model_camada, camadas[0].cubePos[19]);
camadas[0].cubos[2].setModel(camadas[0].model_camada);
cubos[8].model = camadas[idx].cubos[6].model;
cubos[9].model = camadas[idx].cubos[7].model;
cubos[10].model = camadas[idx].cubos[8].model;
cubos[0].model = camadas[idx].cubos[3].model;
cubos[1].model = camadas[idx].cubos[4].model;
cubos[2].model = camadas[idx].cubos[5].model;
cubos[17].model = camadas[idx].cubos[0].model;
cubos[18].model = camadas[idx].cubos[1].model;
cubos[19].model = camadas[idx].cubos[2].model;
}
else if (idx == 1) {
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[3]);
camadas[1].cubos[3].setModel(camadas[1].model_camada);
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[4]);
camadas[1].cubos[5].setModel(camadas[1].model_camada);
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[11]);
camadas[1].cubos[6].setModel(camadas[1].model_camada);
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[12]);
camadas[1].cubos[7].setModel(camadas[1].model_camada);
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[13]);
camadas[1].cubos[8].setModel(camadas[1].model_camada);
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[20]);
camadas[1].cubos[0].setModel(camadas[1].model_camada);
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[21]);
camadas[1].cubos[1].setModel(camadas[1].model_camada);
camadas[1].model_camada = camadas[1].model_center;
camadas[1].model_camada = glm::translate(camadas[1].model_camada, camadas[1].cubePos[22]);
camadas[1].cubos[2].setModel(camadas[1].model_camada);
cubos[11].model = camadas[idx].cubos[6].model;
cubos[12].model = camadas[idx].cubos[7].model;
cubos[13].model = camadas[idx].cubos[8].model;
cubos[3].model = camadas[idx].cubos[3].model;
cubos[26].model = camadas[idx].cubos[4].model;
cubos[4].model = camadas[idx].cubos[5].model;
cubos[20].model = camadas[idx].cubos[0].model;
cubos[21].model = camadas[idx].cubos[1].model;
cubos[22].model = camadas[idx].cubos[2].model;
}
else if (idx == 2) {
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[5]);
camadas[2].cubos[3].setModel(camadas[2].model_camada);
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[7]);
camadas[2].cubos[5].setModel(camadas[2].model_camada);
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[14]);
camadas[2].cubos[6].setModel(camadas[2].model_camada);
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[15]);
camadas[2].cubos[7].setModel(camadas[2].model_camada);
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[16]);
camadas[2].cubos[8].setModel(camadas[2].model_camada);
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[23]);
camadas[2].cubos[0].setModel(camadas[2].model_camada);
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[24]);
camadas[2].cubos[1].setModel(camadas[2].model_camada);
camadas[2].model_camada = camadas[2].model_center;
camadas[2].model_camada = glm::translate(camadas[2].model_camada, camadas[2].cubePos[25]);
camadas[2].cubos[2].setModel(camadas[2].model_camada);
cubos[14].model = camadas[idx].cubos[6].model;
cubos[15].model = camadas[idx].cubos[7].model;
cubos[16].model = camadas[idx].cubos[8].model;
cubos[5].model = camadas[idx].cubos[3].model;
cubos[6].model = camadas[idx].cubos[4].model;
cubos[7].model = camadas[idx].cubos[5].model;
cubos[23].model = camadas[idx].cubos[0].model;
cubos[24].model = camadas[idx].cubos[1].model;
cubos[25].model = camadas[idx].cubos[2].model;
}
else if (idx == 3) {
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[0]);
camadas[3].cubos[1].setModel(camadas[3].model_camada);
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[5]);
camadas[3].cubos[7].setModel(camadas[3].model_camada);
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[8]);
camadas[3].cubos[2].setModel(camadas[3].model_camada);
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[11]);
camadas[3].cubos[5].setModel(camadas[3].model_camada);
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[14]);
camadas[3].cubos[8].setModel(camadas[3].model_camada);
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[17]);
camadas[3].cubos[0].setModel(camadas[3].model_camada);
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[20]);
camadas[3].cubos[3].setModel(camadas[3].model_camada);
camadas[3].model_camada = camadas[3].model_center;
camadas[3].model_camada = glm::translate(camadas[3].model_camada, camadas[3].cubePos[23]);
camadas[3].cubos[6].setModel(camadas[3].model_camada);
cubos[8].model = camadas[idx].cubos[2].model;
cubos[11].model = camadas[idx].cubos[5].model;
cubos[14].model = camadas[idx].cubos[8].model;
cubos[0].model = camadas[idx].cubos[1].model;
cubos[3].model = camadas[idx].cubos[4].model;
cubos[5].model = camadas[idx].cubos[7].model;
cubos[17].model = camadas[idx].cubos[0].model;
cubos[20].model = camadas[idx].cubos[3].model;
cubos[23].model = camadas[idx].cubos[6].model;
}
else if (idx == 4) {
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[1]);
camadas[4].cubos[1].setModel(camadas[4].model_camada);
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[6]);
camadas[4].cubos[7].setModel(camadas[4].model_camada);
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[9]);
camadas[4].cubos[2].setModel(camadas[4].model_camada);
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[12]);
camadas[4].cubos[5].setModel(camadas[4].model_camada);
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[15]);
camadas[4].cubos[8].setModel(camadas[4].model_camada);
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[18]);
camadas[4].cubos[0].setModel(camadas[4].model_camada);
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[21]);
camadas[4].cubos[3].setModel(camadas[4].model_camada);
camadas[4].model_camada = camadas[4].model_center;
camadas[4].model_camada = glm::translate(camadas[4].model_camada, camadas[4].cubePos[24]);
camadas[4].cubos[6].setModel(camadas[4].model_camada);
cubos[9].model = camadas[idx].cubos[2].model;
cubos[12].model = camadas[idx].cubos[5].model;
cubos[15].model = camadas[idx].cubos[8].model;
cubos[1].model = camadas[idx].cubos[1].model;
cubos[26].model = camadas[idx].cubos[4].model;
cubos[6].model = camadas[idx].cubos[7].model;
cubos[18].model = camadas[idx].cubos[0].model;
cubos[21].model = camadas[idx].cubos[3].model;
cubos[24].model = camadas[idx].cubos[6].model;
}
else if (idx == 5) {
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[2]);
camadas[5].cubos[1].setModel(camadas[5].model_camada);
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[7]);
camadas[5].cubos[7].setModel(camadas[5].model_camada);
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[10]);
camadas[5].cubos[2].setModel(camadas[5].model_camada);
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[13]);
camadas[5].cubos[5].setModel(camadas[5].model_camada);
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[16]);
camadas[5].cubos[8].setModel(camadas[5].model_camada);
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[19]);
camadas[5].cubos[0].setModel(camadas[5].model_camada);
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[22]);
camadas[5].cubos[3].setModel(camadas[5].model_camada);
camadas[5].model_camada = camadas[5].model_center;
camadas[5].model_camada = glm::translate(camadas[5].model_camada, camadas[5].cubePos[25]);
camadas[5].cubos[6].setModel(camadas[5].model_camada);
cubos[10].model = camadas[idx].cubos[2].model;
cubos[13].model = camadas[idx].cubos[5].model;
cubos[16].model = camadas[idx].cubos[8].model;
cubos[2].model = camadas[idx].cubos[1].model;
cubos[4].model = camadas[idx].cubos[4].model;
cubos[7].model = camadas[idx].cubos[7].model;
cubos[19].model = camadas[idx].cubos[0].model;
cubos[22].model = camadas[idx].cubos[3].model;
cubos[25].model = camadas[idx].cubos[6].model;
}
else if (idx == 6) {
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[9]);
camadas[6].cubos[1].setModel(camadas[6].model_camada);
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[15]);
camadas[6].cubos[7].setModel(camadas[6].model_camada);
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[10]);
camadas[6].cubos[2].setModel(camadas[6].model_camada);
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[13]);
camadas[6].cubos[5].setModel(camadas[6].model_camada);
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[16]);
camadas[6].cubos[8].setModel(camadas[6].model_camada);
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[8]);
camadas[6].cubos[0].setModel(camadas[6].model_camada);
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[11]);
camadas[6].cubos[3].setModel(camadas[6].model_camada);
camadas[6].model_camada = camadas[6].model_center;
camadas[6].model_camada = glm::translate(camadas[6].model_camada, camadas[6].cubePos[14]);
camadas[6].cubos[6].setModel(camadas[6].model_camada);
cubos[10].model = camadas[idx].cubos[2].model;
cubos[13].model = camadas[idx].cubos[5].model;
cubos[16].model = camadas[idx].cubos[8].model;
cubos[9].model = camadas[idx].cubos[1].model;
cubos[12].model = camadas[idx].cubos[4].model;
cubos[15].model = camadas[idx].cubos[7].model;
cubos[8].model = camadas[idx].cubos[0].model;
cubos[11].model = camadas[idx].cubos[3].model;
cubos[14].model = camadas[idx].cubos[6].model;
}
else if (idx == 7) {
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[1]);
camadas[7].cubos[1].setModel(camadas[7].model_camada);
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[6]);
camadas[7].cubos[7].setModel(camadas[7].model_camada);
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[2]);
camadas[7].cubos[2].setModel(camadas[7].model_camada);
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[4]);
camadas[7].cubos[5].setModel(camadas[7].model_camada);
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[7]);
camadas[7].cubos[8].setModel(camadas[7].model_camada);
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[0]);
camadas[7].cubos[0].setModel(camadas[7].model_camada);
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[3]);
camadas[7].cubos[3].setModel(camadas[7].model_camada);
camadas[7].model_camada = camadas[7].model_center;
camadas[7].model_camada = glm::translate(camadas[7].model_camada, camadas[7].cubePos[5]);
camadas[7].cubos[6].setModel(camadas[7].model_camada);
cubos[2].model = camadas[idx].cubos[2].model;
cubos[4].model = camadas[idx].cubos[5].model;
cubos[7].model = camadas[idx].cubos[8].model;
cubos[1].model = camadas[idx].cubos[1].model;
cubos[26].model = camadas[idx].cubos[4].model;
cubos[6].model = camadas[idx].cubos[7].model;
cubos[0].model = camadas[idx].cubos[0].model;
cubos[3].model = camadas[idx].cubos[3].model;
cubos[5].model = camadas[idx].cubos[6].model;
}
else if (idx == 8) {
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[18]);
camadas[8].cubos[1].setModel(camadas[8].model_camada);
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[24]);
camadas[8].cubos[7].setModel(camadas[8].model_camada);
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[19]);
camadas[8].cubos[2].setModel(camadas[8].model_camada);
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[22]);
camadas[8].cubos[5].setModel(camadas[8].model_camada);
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[25]);
camadas[8].cubos[8].setModel(camadas[8].model_camada);
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[17]);
camadas[8].cubos[0].setModel(camadas[8].model_camada);
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[20]);
camadas[8].cubos[3].setModel(camadas[8].model_camada);
camadas[8].model_camada = camadas[8].model_center;
camadas[8].model_camada = glm::translate(camadas[8].model_camada, camadas[8].cubePos[23]);
camadas[8].cubos[6].setModel(camadas[8].model_camada);
cubos[19].model = camadas[idx].cubos[2].model;
cubos[22].model = camadas[idx].cubos[5].model;
cubos[25].model = camadas[idx].cubos[8].model;
cubos[18].model = camadas[idx].cubos[1].model;
cubos[21].model = camadas[idx].cubos[4].model;
cubos[24].model = camadas[idx].cubos[7].model;
cubos[17].model = camadas[idx].cubos[0].model;
cubos[20].model = camadas[idx].cubos[3].model;
cubos[23].model = camadas[idx].cubos[6].model;
}
int cur_ang = (int)camadas[idx].ang_;
if (cur_ang && cur_ang % 90 == 0) {
if (cur_ang == 90) camadas[idx].ang_ = 0;
camadas[idx].girar = 0;
}
}
}
void rotCamada(int& idx, bool rotation) {
int n_idx = idx - 1;
int mov = 0;
if (n_idx > -1) {
if (camadas[n_idx].animation && camadas[n_idx].girar == 0) {
camadas[n_idx].animation = 0;
camadas[n_idx].girar = 0;
idx = 0;
updatefinalCamadas(n_idx, camadas[n_idx].orientation, rotation,mov);
}
else {
camadas[n_idx].animation = 1;
camadas[n_idx].girar = 1;
camadas[n_idx].set_cubes_rot(rotation);
updateCamadas(n_idx);
}
}
}
int rotCamada02(int& idx, bool rotation,int& mov_cam) {
int n_idx = idx - 1;
if (n_idx > -1) {
if (camadas[n_idx].animation && camadas[n_idx].girar == 0) {
camadas[n_idx].animation = 0;
camadas[n_idx].girar = 0;
idx = 0;
updatefinalCamadas(n_idx, camadas[n_idx].orientation, rotation, mov_cam);
return 1;
}
else {
camadas[n_idx].animation = 1;
camadas[n_idx].girar = 1;
camadas[n_idx].set_cubes_rot(rotation);
updateCamadas(n_idx);
return 2;
}
}
return 3;
}
int parser_mov(int& camada_giro, bool& rotation, string& moves_cp,int& mov_cam) {
if (!flag_sol) {
borr = 1;
if ('\n' == moves_cp[0] || ' ' == moves_cp[0]) {
moves_cp.erase(0, 1);
cout << "Solucionado?\n";
return 0;
}
m = moves_cp[0];
if (moves_cp.size() > 1) {
if (moves_cp[1] == '2') {
m += moves_cp[1];
borr = 0;
}
}
if (m == "R") {
camada_giro = 6;
rotation = 0;
}
else if (m == "L") {
camada_giro = 4;
rotation = 1;
}
else if (m == "U") {
camada_giro = 1;
rotation = 0;
}
else if (m == "D") {
camada_giro = 3;
rotation = 1;
}
else if (m == "F") {
camada_giro = 7;
rotation = 1;
}
else if (m == "W") {
camada_giro = 9;
rotation = 0;
}
//////
else if (m == "r") {
camada_giro = 6;
rotation = 1;
}
else if (m == "l") {
camada_giro = 4;
rotation = 0;
}
else if (m == "u") {
camada_giro = 1;
rotation = 1;
}
else if (m == "d") {
camada_giro = 3;
rotation = 0;
}
else if (m == "f") {
camada_giro = 7;
rotation = 0;
}
else if (m == "w") {
camada_giro = 9;
rotation = 1;
}
flag_sol = 1;
}
int ind = rotCamada02(camada_giro, rotation,mov_cam);
if (ind == 1) {
if (borr) moves_cp.erase(0, 1);
else {
moves_cp.erase(0, 2);
borr = 1;
}
flag_sol = 0;
}
}
int parser_mov02(int& camada_giro, bool& rotation, string& moves_cp) {
if (!flag_sol) {
borr = 1;
if ('\n' == moves_cp[0] || ' ' == moves_cp[0]) {
moves_cp.erase(0, 1);
return 0;
}
m = moves_cp[0];
if (moves_cp.size() > 1) {
if (moves_cp[1] == '2') {
m += moves_cp[1];
borr = 0;
}
}
if (m == "Z") {
camada_giro = 1;
rotation = 1;
}
else if (m == "V") {
camada_giro = 4;
rotation = 1;
}
else if (m == "J") {
camada_giro = 7;
rotation = 1;
}
flag_sol = 1;
}
int mov = 0;
int ind = rotCamada02(camada_giro, rotation,mov);
if (ind == 1) {
if (borr) moves_cp.erase(0, 1);
else {
moves_cp.erase(0, 2);
borr = 1;
}
flag_sol = 0;
}
}
void readSolution() {
ifstream file("sol.dat");
stringstream buffer;
buffer << file.rdbuf();
sol_movs = buffer.str();
cout << "Solucion: " << sol_movs <<"\n";
}
void solutionCube(bool &acc,string& word) {
if (acc) {
system("Rubik-solver\\bin\\Rubik.exe stateCub.dat sol.dat");
readSolution();
word = sol_movs;
acc = 0;
}
}
void drawCubeRubik(Shader shaderc,bool op=0) {
for (int i = 0; i < 26; i++) {
glm::mat4 model;
glm::mat4 model_text;
model = cubos[i].getModelMatrix(1);
//model = glm::translate(model, glm::vec3(0.0,-5.0,0.0));
model_text = cubos[i].getModelText();
shaderc.setMat4("model", model);
if(op) cubos[i].drawCubeText();
else cubos[i].drawCubeColors(shaderc);
}
}
void drawCubeRubik_(Shader shaderc, bool op, glm::vec3 pos) {
for (int i = 0; i < 26; i++) {
glm::mat4 model;
model = cubos[i].getModelMatrix(1);
model = glm::translate(model, pos);
shaderc.setMat4("model", model);
if (op) cubos[i].drawCubeText();
else cubos[i].drawCubeColors(shaderc);
}
}
};
#endif
|
HectorIdme/Cubo_Rubik
|
Rubik-solver/include/defineRubik.h
|
<gh_stars>1-10
/**
* @file defineRubik.h
* @brief Definition of a rubik's cube
*
* @author <NAME>
* @date 20/05/2016
*
*/
#ifndef def_rubik_h
#define def_rubik_h
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
/**
* @struct Center
* @brief Central sticker of a face.
*
*/
struct Center{
char center;
};
/**
* @struct Edge
* @brief Piece with two stickers.
*
*/
struct Edge{
char up, down;
};
/**
* @struct Corner
* @brief Piece with three stickers, the orientation doesn't change.
*
*/
struct Corner{
char up, left, right;
};
/**
* @class Class to interact with an instance of Rubik's Cube
*
*/
class Rubik{
private:
/**
* @brief Centers of rubik's cube
* \note Order of centers: top(0), frontal(1), right(2), back(3), left(4), bottom(5)
*
*/
Center center[6];
/**
* @brief Edges of rubik's cube
* \note Order of edges:
* top(0, 1, 2, 3) and bottom(4, 5, 6, 7), central ring(8, 9, 10, 11)
*
*/
Edge edge[12];
/**
* @brief Corners of rubik's cube
* \note Order of corners:
* top(0, 1, 2, 3) and bottom(4, 5, 6, 7)
*
*/
Corner corner[8];
// Auxiliary functions
/**
* @brief Develop each movement in natural language
* @param vector<char>& solution Movements to explain, part of the real solution
* @param const unsigned int& movement First movement to explain
* @return void
* @pre char of solution are limited in class
* @pre movement < solution.size()
* @see Movements
*
*/
void explainMovements(vector<char>& solution, unsigned int& movement) const;
/**
* @brief Calculate number asociated
* @param const char& c
* @return int asociated
* @retval [1, 6]
* @pre c limited with rubik's colours
*
*/
int equivalentNumber(const char& c) const;
/**
* @brief Look for specific edge
* @param const char& ar
* @param const char& ab
* @return int
* @retval [0, 11]
* @pre ar && ab valid colours with centers not opposite
* @see Edge
*
*/
int searchEdge(const char& ar, const char& ab) const;
/**
* @brief Look for specific specific corner
* @param const char& a
* @param const char& iz
* @param const char& de
* @return int
* @retval [0, 7]
* @pre a, iz, de valid colours with center not opposite
* @see Corner
*
*/
int searchCorner(const char& a, const char& iz, const char& de) const;
/**
* @brief Execution of sec.size() movements in string sec
* @param string sec string with movements
* @param vector<char>& solution where we will append movements from sec
* @return void
* @pre Valid chars in string
* @see explainMovements()
*
*/
void sequence(const string& sec, vector<char>& solution);
// Parts of the solution
/**
* @brief It complete top face (white)
* @param vector<char>& solution will store the solution
* @param vector<char>& solution
* @return void
* @pre solution.size() == 0, it will be deleted
*
*/
void firstStep(vector<char>& solution);
/**
* @brief First part of top face
* @param vector<char>& solution
* @return void
* @see firstStep()
*
*/
void whiteCross(vector<char>& solution);
/**
* @brief First three corners of top face
* @param vector<char>& solution
* @return void
* @pre firstStep()
* @see firstStep()
*
*/
void cornersFirstStep(vector<char>& solution);
/**
* @brief Central ring of rubik's cube
* @param vector<char>& solution
* @return void
* @pre firstStep()
* @see thirdStep()
*
*/
void secondStep(vector<char>& solution);
/**
* @brief Last part of solution
* @param vector<char>& solution
* @return void
* @pre firstStep()
* @pre secondStep()
*
*/
void thirdStep(vector<char>& solution);
/**
* @brief First part of bottom face
* @param vector<char>& solution
* @return void
* @see thirdStep()
*
*/
void yellowCross(vector<char>& solution);
/**
* @brief Last four corners
* @param vector<char>& solution
* @return void
* @pre yellowCross()
*
*/
void finalCorners(vector<char>& solution);
/**
* @brief It moves corner to their position
* @param vector<char>& solution
* @return void
* @see finalCorners()
*
*/
void permutationFinalCorners(vector<char>& solution);
/**
* @brief Last step
* @param vector<char>& solution
* @return void
* @pre permutationFinalCorners()
* @see
*
*/
void positionFinalCorners(vector<char>& solution);
public:
/**
* @brief Constructor without arguments
* @see validRubik()
*
*/
Rubik();
/**
* @brief Constructor with an instance of Rubik class
* @param const Rubik& rubik
* @pre *this != &rubik
*
*/
Rubik(const Rubik& rubik);
/**
* @brief It builds a random rubik
* @param const int &number of random movements
* @return void
* \note It is modified
*
*/
void mixRubik(const int& number=300);
/**
* @brief Check if our rubik's cube is solved
* @return bool
* @see validRubik()
*
*/
bool isSolved() const;
/**
* @brief Check if there are logic errors in colour distribution
* @return int
* @retval -1 wrong centers
* @retval -2 wrong edges
* @retval -3 wrong corners
*
*/
int logicErrors() const;
/**
* @brief Error modifier
* @return void
* @pre readRubik()
*
*/
void correctMistakes();
// Movements
/**
* @brief Move right side backward.
* @param vector<char>& solution
* @return void
* @see r()
*
*/
void R(vector<char>& solution);
/**
* @brief Move right side backward two times
* @param vector<char>& solution
* @return void
*
*/
void R2(vector<char>& solution);
/**
* @brief Move right side to you
* @param vector<char>& solution
* @return
* @see R()
*
*/
void r(vector<char>& solution);
/**
* @brief Move left side to you
* @param vector<char>& solution
* @return void
* @see l()
*
*/
void L(vector<char>& solution);
/**
* @brief Move left side to you two times
* @param vector<char>& solution
* @return void
*
*/
void L2(vector<char>& solution);
/**
* @brief Move left side backward
* @param vector<char>& solution
* @return void
* @see L()
*
*/
void l(vector<char>& solution);
/**
* @brief Move down side right
* @param vector<char>& solution
* @return void
* @see d()
*
*/
void D(vector<char>& solution);
/**
* @brief Move down side right two times
* @param vector<char>& solution
* @return void
*
*/
void D2(vector<char>& solution);
/**
* @brief Move down side left
* @param vector<char>& solution
* @return void
* @see D()
*
*/
void d(vector<char>& solution);
/**
* @brief Move top side left
* @param vector<char>& solution
* @return void
* @see u()
*
*/
void U(vector<char>& solution);
/**
* @brief Move top side left two times
* @param vector<char>& solution
* @return void
*
*/
void U2(vector<char>& solution);
/**
* @brief Move top side right
* @param vector<char>& solution
* @return void
* @see U()
*
*/
void u(vector<char>& solution);
/**
* @brief Move frontal side in clockwise
* @param vector<char>& solution
* @return void
* @see f()
*
*/
void F(vector<char>& solution);
/**
* @brief Move frontal side in clockwise two times
* @param vector<char>& solution
* @return void
*
*/
void F2(vector<char>& solution);
/**
* @brief Move frontal side, not in clockwise
* @param vector<char>& solution
* @return void
* @see F()
*
*/
void f(vector<char>& solution);
/**
* @brief Move back side left
* @param vector<char>& solution
* @return void
* @see b()
*
*/
void B(vector<char>& solution);
/**
* @brief Move back side left two times
* @param vector<char>& solution
* @return void
*
*/
void B2(vector<char>& solution);
/**
* @brief Move back side right
* @param vector<char>& solution
* @return void
* @see B()
*
*/
void b(vector<char>& solution);
// Solve
/**
* @brief It solves rubik's cube in intervals
* @param vector<char>& solution
* @return void
* @pre solution empty, it's modified
* @see solve()
*
*/
void solveStepByStep(vector<char>& solution);
/**
* @brief It solves rubik cube with private auxiliary functions
* @param vector<char>& solution
* @return void
* @pre solution empty, it's modified
* @see solveStepByStep()
*
*/
void solve(vector<char>& solution, const char& method='B');
// Input && output
/**
* @brief Rubik example file
* @return void
*
*/
static void fileExample();
/**
* @brief It export rubik's cube in a format readable for readRubik)=
* @param std::ostream& os=cout
* @return void
* @see readRubik()
*
*/
void exportRubik(std::ostream& os=cout) const;
/**
* @brief Export steps to solve rubik's cube
* @param std::ostream& os=cout
* @return void
* @pre (logicErrors() == 0)
* @see exportSupervisedSolution()
*
*/
void exportSolution(std::ostream& os=cout) const;
/**
* @brief Export steps with explanations
* @param std::ostream& os=cout
* @return void
* @pre (logicErrors() == 0)
* @see exportSolution()
*
*/
void exportSupervisedSolution(std::ostream& os=cout) const;
/**
* @brief Print sticker with specific colour
* @param const char& c
* @return void
* @pre valid char
*
*/
void printColour(const char& c) const;
/**
* @brief Print a rubik's cube with numbers to correct mistakes
* @param std::ostream& os=cout
* @return void
* @see correctMistakes()
*
*/
//static
static void printNumbers(std::ostream& os=cout);
/**
* @brief Print rubik's cube with respective colours
* @return void
* @see printColour()
*
*/
void printAll() const;
/**
* @brief Read specific sticker from rubik's cube
* \note Rubik is modified
* @param char& c, is modified
* @param std::istream& is=cin
* @return void
* @pre char& c is a sticker of the instance
* @see readRubik()
*
*/
void readSticker(char& c, std::istream& is=cin);
/**
* @brief Read rubik's cube
* \note It's modified
* @param std::istream& is=cin
* @return void
* @pre Readable istream with correct rubik's format
* @see readSticker()
*
*/
void readRubik(std::istream& is=cin);
// Getter
/**
* @brief Getter of center piece
* @param const int& position
* @return Center
* @pre Valid position
* @see Center
*
*/
Center getCenter(const int& position) const;
/**
* @brief Getter of specific edge
* @param const int& position
* @return Edge
* @pre Valid position
* @see Edge
*
*/
Edge getEdge(const int& position) const;
/**
* @brief Getter of specific corner
* @param const int& position
* @return Corner
* @pre Valid position
* @see Corner
*
*/
Corner getCorner(const int& position) const;
/**
* @brief It creates a random rubik's cube
* @return Rubik
*
*/
static Rubik randomRubik();
// Operators
/**
* @brief Assigment operator
* \note It's modified
* @param const Rubik& r
* @return Rubik&
* @retval *this
* @pre r different rubik's cube
* @see operator ==
*
*/
Rubik& operator = (const Rubik& r);
/**
* @brief Operator ==
* @param const Rubik& r
* @return bool
* @pre r different rubik's cube
*
*/
bool operator == (const Rubik& rubik);
/**
* @brief Operator !=
* @param const Rubik& r
* @return bool
* @pre r different rubik's cube
*
*/
bool operator != (const Rubik& rubik);
};
/**
* @brief Ostream in readable format
* @param std::ostream& os
* @param const Rubik& rubik
* @return std::ostream&
*
*/
std::ostream& operator << (std::ostream& os, const Rubik& rubik);
/**
* @brief Istream of a rubik's cube in readable format
* @param std::istraem& is
* @param Rubik& rubik, it's modified
* @return std::istream&
*
*/
std::istream& operator >>(std::istream& is, Rubik &rubik);
// Presentation
/**
* @brief Guide of program
* @return void
*
*/
void guide();
/**
* @brief Presentation of program
* @return void
*
*/
void presentation();
/**
* @brief Explication of valid movements
* @return void
*
*/
void movements();
/**
* @brief Explication of program's arguments
* @param string name of main program
* @return void
*
*/
void arguments(string name);
#endif
|
HectorIdme/Cubo_Rubik
|
texture.h
|
#ifndef TEXTURE_H
#define TEXTURE_H
#include <glad/glad.h>
#include <glm/glm.hpp>
#include "std_image.h"
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
class Texture{
public:
int width, height, nrChannels;
unsigned char* data;
Texture::Texture(const char* texturePath, unsigned int &ID,bool format=0) {
glBindTexture(GL_TEXTURE_2D, ID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_set_flip_vertically_on_load(true);
data = stbi_load(texturePath, &width, &height, &nrChannels, 0);
if (data) {
if (format) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
else glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else { std::cout << "Failed to load texture\n"; }
stbi_image_free(data);
}
};
#endif
|
nocsonic/cordova-plugin-nocsonicmedia-ios
|
src/ios/CDVAudions.h
|
<filename>src/ios/CDVAudions.h
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioServices.h>
#import <AVFoundation/AVFoundation.h>
#import <Cordova/CDVPlugin.h>
enum CDVNocSonicMixerError {
MEDIA_ERR_ABORTED = 1,
MEDIA_ERR_NETWORK = 2,
MEDIA_ERR_DECODE = 3,
MEDIA_ERR_NONE_SUPPORTED = 4
};
typedef NSUInteger CDVNocSonicMixerError;
enum CDVNocSonicMixerStates {
NSMIXER_NONE = 0,
NSMIXER_SONICLOOP_LOADED = 1,
NSMIXER_SONICLOOP_PLAYING = 2,
NSMIXER_SONICLOOP_PAUSED = 3,
NSMIXER_SONICLOOP_STOPPED = 4,
NSMIXER_SONICLOOP_REWIND = 5,
NSMIXER_SONICLOOP_VOLUME = 6,
NSMIXER_SONICLOOP_RELEASE = 7,
NSMIXER_RECORDSESSION_READY = 8,
NSMIXER_RECORDSESSION_STARTED = 9,
NSMIXER_RECORDSESSION_IN_PROGESS = 10,
NSMIXER_RECORDSESSION_STOPPED = 11,
NSMIXER_RECORDSESSION_INPUTVOLUME = 12,
NSMIXER_MIXINGSESSION_READY = 13,
NSMIXER_MIXINGSESSION_PLAYING = 14,
NSMIXER_MIXINGSESSION_PAUSED = 15,
NSMIXER_MIXINGSESSION_STOPPED = 16,
NSMIXER_MIXINGSESSION_REWIND = 17,
NSMIXER_MIXINGSESSION_SONICVOLUME = 18,
NSMIXER_MIXINGSESSION_NOCVOLUME = 19,
NSMIXER_MIXINGSESSION_DESTROYSONIC = 20,
NSMIXER_MIXINGSESSION_RELEASESONIC = 21,
NSMIXER_MIXINGSESSION_DESTROYNOC = 22,
NSMIXER_MIXINGSESSION_RELEASENOC = 23,
NSMIXER_MIXINGSESSION_REMOVEDITS = 24,
NSMIXER_MIXINGSESSION_MERGE = 25,
NSMIXER_MASTERMIX_READY = 26,
NSMIXER_MASTERMIX_PLAYING = 27,
NSMIXER_MASTERMIX_PAUSED = 28,
NSMIXER_MASTERMIX_STOPPED = 29,
NSMIXER_MASTERMIX_DELETE = 30,
NSMIXER_MASTERMIX_VOLUME = 31,
NSMIXER_MASTERMIX_REWIND = 32,
NSMIXER_MASTERMIX_SEEK_POSITION = 33,
NSMIXER_MASTERMIX_RELEASE = 34,
NSMIXER_MASTERMIX_PROMOTE_TO_FILE = 35,
NSMIXER_PROMOTEDFILE_READY = 36,
NSMIXER_PROMOTEDFILE_PLAYING = 37,
NSMIXER_PROMOTEDFILE_PAUSED = 38,
NSMIXER_PROMOTEDFILE_STOPPED = 39,
NSMIXER_PROMOTEDFILE_VOLUME = 40,
NSMIXER_PROMOTEDFILE_SEEK_POSITION = 41,
NSMIXER_PROMOTEDFILE_DELETE = 42,
NSMIXER_PROMOTEDFILE_RELEASE = 43,
NSMIXER_PROMOTEDFILE_LOCATION = 44
};
typedef NSUInteger CDVNocSonicMixerStates;
enum CDVNocSonicMixeMsg {
NSMIXER_STATE = 1,
NSMIXER_SONICLOOP_VU_METER= 2,
NSMIXER_VOCALINPUT_VU_METER = 3,
NSMIXER_NOCTRACK_VU_METER = 4,
NSMIXER_SONICTRACK_VU_METER = 5,
NSMIXER_MASTERMIX_VU_METER = 6,
NSMIXER_MASTERMIX_POSITION = 7,
NSMIXER_MASTERMIX_DURATION = 8,
NSMIXER_PROMOTEDFILE_VU_METER = 9,
NSMIXER_PROMOTEDFILE_DURATION = 10,
NSMIXER_PROMOTEDFILE_POSITION = 11,
NSMIXER_PROMOTEDFILE_PATH = 12,
NSMIXER_ERROR = 99,
};
typedef NSUInteger CDVNocSonicMixeMsg;
@interface CDVAudioMixerPlayer : AVAudioPlayer
{
NSString* mediaId;
}
@property (nonatomic, copy) NSString* mediaId;
@end
@interface CDVAudioMixerRecorder : AVAudioRecorder
{
}
@property (nonatomic, copy) NSString* mediaId;
@end
@interface CDVAudioMixerFile : NSObject
{
}
@property (nonatomic, strong) NSString* resourcePath;
@property (nonatomic, strong) NSURL* resourceURL;
@property (nonatomic, strong) CDVAudioMixerPlayer* player;
@property (nonatomic, strong) NSNumber* volume;
@property (nonatomic, strong) CDVAudioMixerRecorder* recorder;
@end
@interface CDVAudions : CDVPlugin <AVAudioPlayerDelegate, AVAudioRecorderDelegate>
{
}
@property (nonatomic, strong) NSMutableDictionary* soundCache;
@property (nonatomic, strong) AVAudioSession* avSession;
//rythym selector
- (void)loadedSonicTrack:(CDVInvokedUrlCommand*)command;
- (void)startPlayingSonicLoop:(CDVInvokedUrlCommand*)command;
- (void)pauseSonicLoop:(CDVInvokedUrlCommand*)command;
- (void)stopSonicLoop:(CDVInvokedUrlCommand*)command;
- (void)sonicLoopRewind:(CDVInvokedUrlCommand*)command;
- (void)setSonicLoopVolume:(CDVInvokedUrlCommand*)command;
- (void)getSonicLoopMeter:(CDVInvokedUrlCommand*)command;
- (void)sonicLoopRelease:(CDVInvokedUrlCommand*)command;
//Recording Session View
- (void)startNocRecordingSession:(CDVInvokedUrlCommand*)command;
- (void)startRecordingAudio:(CDVInvokedUrlCommand*)command;
- (void)stopNocRecordingSession:(CDVInvokedUrlCommand*)command;
- (void)setInputAmplitude:(CDVInvokedUrlCommand*)command;
- (void)getVocalInputMeter:(CDVInvokedUrlCommand*)command;
// 2 Track Mixing Session
- (void)start2TrackMixingSession:(CDVInvokedUrlCommand*)command;
- (void)playTwoTracks:(CDVInvokedUrlCommand*)command;
- (void)pauseTwoTracks:(CDVInvokedUrlCommand*)command;
- (void)stopTwoTracks:(CDVInvokedUrlCommand*)command;
- (void)rewindTwoTracks:(CDVInvokedUrlCommand*)command;
- (void)setSonicBufferTrackVolume:(CDVInvokedUrlCommand*)command;
- (void)setNocBufferTrackVolume:(CDVInvokedUrlCommand*)command;
- (void)getSonicTrackMeter:(CDVInvokedUrlCommand*)command;
- (void)getNocTrackMeter:(CDVInvokedUrlCommand*)command;
- (void)deleteSonicTrackBuffer:(CDVInvokedUrlCommand*)command;
- (void)releaseSonicTrackBuffer:(CDVInvokedUrlCommand*)command;
- (void)deleteNocTrackBuffer:(CDVInvokedUrlCommand*)command;
- (void)releaseNocTrackBuffer:(CDVInvokedUrlCommand*)command;
- (void)removeNocSonicMidiEdits:(CDVInvokedUrlCommand*)command;
- (void)mergeNocSonicMidiEdits:(CDVInvokedUrlCommand*)command;
// Master Creation Session
- (void)startMasterMixSession:(CDVInvokedUrlCommand*)command;
- (void)playMasterMix:(CDVInvokedUrlCommand*)command;
- (void)pauseMasterMix:(CDVInvokedUrlCommand*)command;
- (void)stopMasterMix:(CDVInvokedUrlCommand*)command;
- (void)rewindMasterMix:(CDVInvokedUrlCommand*)command;
- (void)setMasterMixVolume:(CDVInvokedUrlCommand*)command;
- (void)getMasterMixMeter:(CDVInvokedUrlCommand*)command;
- (void)getCurrentMasterMixPosition:(CDVInvokedUrlCommand*)command;
- (void)deleteMasterMix:(CDVInvokedUrlCommand*)command;
- (void)releaseMasterMix:(CDVInvokedUrlCommand*)command;
- (void)promoteMasterMix:(CDVInvokedUrlCommand*)command;
// Master Promotion Session
- (void)startPromotedFileSession:(CDVInvokedUrlCommand*)command;
- (void)playPromotedFile:(CDVInvokedUrlCommand*)command;
- (void)pausePromotedFile:(CDVInvokedUrlCommand*)command;
- (void)stopPromotedFile:(CDVInvokedUrlCommand*)command;
- (void)getPromotedFilePosition:(CDVInvokedUrlCommand*)command;
- (void)promotedFileSeekTo:(CDVInvokedUrlCommand*)command;
- (void)setPromotedFileVolume:(CDVInvokedUrlCommand*)command;
- (void)getPromotedFileMeter:(CDVInvokedUrlCommand*)command;
- (void)releasePromotedFile:(CDVInvokedUrlCommand*)command;
- (void)deletePromotedFile:(CDVInvokedUrlCommand*)command;
- (void)getPromotedFileLocation:(CDVInvokedUrlCommand*)command;
// Two Track Mixing Session
- (BOOL)hasNocAudioSession;
// helper methods
- (NSURL*)urlForNocRecording:(NSString*)resourcePath;
- (NSURL*)urlForNocPlaying:(NSString*)resourcePath;
- (CDVAudioMixerFile*)audioNocFileForResource:(NSString*)resourcePath withId:(NSString*)mediaId doValidation:(BOOL)bValidate forRecording:(BOOL)bRecord;
- (BOOL)prepareToPlayNoc:(CDVAudioMixerFile*)audioFile withId:(NSString*)mediaId;
- (NSString*)createNocSonicMixErrorWithCode:(CDVNocSonicMixerError)code message:(NSString*)message;
@end
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Construction/ConstructionManager.h
|
// No copyright - copy as you please
#pragma once
#include <GameFramework/Actor.h>
#include "ConstructionManager.generated.h"
UCLASS()
class TD2020_API AConstructionManager : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AConstructionManager();
protected:
// Called when the game staTD2020 or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enviroment/DayNightCycle.h
|
// No copyright - copy as you please
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "DayNightCycle.generated.h"
class ADirectionalLight;
class AMySkySphere;
class AMyGameState;
class USceneComponent;
class UStaticMeshComponent;
class UMaterial;
class UCurveLinearColor;
UCLASS()
class TD2020_API ADayNightCycle : public AActor
{
GENERATED_BODY()
public:
// Components
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components")
USceneComponent* Scene;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components")
UStaticMeshComponent* Moon;
// references
UPROPERTY(EditAnywhere, Category = "References")
ADirectionalLight* SunLight;
UPROPERTY(EditAnywhere, Category = "References")
ADirectionalLight* MoonLight;
UPROPERTY(EditAnywhere, Category = "References")
AMySkySphere* SkySphere;
// properties
// 3600 in hours
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Properties)
float TimeUnit;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
int SunDays;
// The hour of sun position
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float SunDrive;
// Default to 24h
UPROPERTY(EditAnywhere, Category = "Sun")
float SunDayDuration;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Properties)
float Clockwork;
// default to 365.25
UPROPERTY(EditAnywhere, Category = "Sun")
float SunYearDuration;
// Defaults to -23.5f -> value of Sun max declination
UPROPERTY(EditAnywhere, Category = "Sun")
float MaxDeclination;
// Current sun declination - if positive - Summer
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float SunDeclination;
// Current latitude (Ljubljana is at 46)
UPROPERTY(EditAnywhere, Category = "Sun")
float Latitude;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float SunHalfDayLight;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float SunHalfNight;
// Highpoint of x^2 graph will be ((at midnight or mid-noon)
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float Shift;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float Length;
// Default to -1.0f -> 1 or 0 if day or night
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float DayNightFlip;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float SunPitch;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float SunYaw;
// todo comment
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float SunDeclinationDrive;
// switch to turn off day night cycle
UPROPERTY(EditAnywhere, Category = Properties)
bool UseDayNightCycle;
// Is -1 if on southern hemisphere or 1 on northern
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Sun")
float EquatorFlip;
// toggle if want to use polar day and polar night
UPROPERTY(EditAnywhere, Category = "Sun")
bool SunPolar;
UPROPERTY(EditAnywhere, Category = "Time")
int Seconds;
UPROPERTY(EditAnywhere, Category = "Time")
int Minutes;
UPROPERTY(EditAnywhere, Category = "Time")
int Hours;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Time")
TArray<int> GameTime;
// every time (for one tick) this will be 1
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Properties)
int DayTick;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Calendar")
TArray<int> GameDate;
UPROPERTY(EditAnywhere, Category = "Time")
bool UseSystemTime;
UPROPERTY(EditAnywhere, Category = "Calendar", meta = (UIMin = "1", UIMax = "31"))
int Day;
UPROPERTY(EditAnywhere, Category = "Calendar", meta = (UIMin = "1", UIMax = "12"))
int Month;
UPROPERTY(EditAnywhere, Category = "Calendar", meta = (UIMin = "1"))
int Year;
UPROPERTY(EditAnywhere, Category = "Calendar")
bool UseSystemDate;
UPROPERTY(EditAnywhere, Category = Properties)
bool EarthLike;
UPROPERTY(EditAnywhere, Category = "Moon")
float MoonDayDuration;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonDeclination;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonDeclinationDrive;
// Time between two full moons
UPROPERTY(EditAnywhere, Category = "Moon")
float MoonYearDuration;
// plane that moon rotates on - tilted by 5 degrees
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonInclination;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonEquatorFlip;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonDrive;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonHalfDayLight;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonHalfNight;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonDayNightFlip;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonShift;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonLength;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonPitch;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Moon")
float MoonYaw;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Moon")
UMaterialInstanceDynamic* MoonMaterialInstance;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Moon")
UMaterial* MoonMaterial;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Moon")
UCurveLinearColor* SkyColor;
// Sets default values for this actor's properties
ADayNightCycle();
// Called every frame
virtual void Tick(float DeltaTime) override;
virtual void OnConstruction(const FTransform& Transform) override;
protected:
// Called when the game staTD2020 or when spawned
virtual void BeginPlay() override;
private:
// if init is valid
bool Valid;
void SunTrajectory();
void MoonTrajectory();
void Clock();
void Calendar();
bool Validate();
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Libraries/FunctionLibrary.h
|
// No copyright - copy as you please
#pragma once
#include <Kismet/BlueprintFunctionLibrary.h>
#include "FunctionLibrary.generated.h"
class ACameraPawnController;
class APlayerController;
class ACameraPawn;
class UBoxComponent;
class UStaticMeshComponent;
class USceneComponent;
UCLASS()
class TD2020_API UFunctionLibrary : public UBlueprintFunctionLibrary
{
GENERATED_BODY()
public:
// todo comment
// Parameters
// IN Camera Pawn Controller object reference
// IN float Sight Distance
// OUT FVector Location
//UFUNCTION(Category = FunctionLibrary, BlueprintPure)
// static void SetCursorWorldPosition(const ACameraPawnController* CameraPawnController, const float SightDistance,
// FVector& Location);
// Controls camera pan around pawn
// Parameters
// IN Camera Pawn
// IN float Min Pan Y - set to -180 if don't want to use it
// IN float Max Pan Y - set to 180 if don't want to use it
// IN float Sensitivity
// IN float Camera X - Mouse X movement [0 - 1]
// IN float Camera Y - Mouse Y movement [0 - 1]
//UFUNCTION(Category = FunctionLibrary, BlueprintCallable)
// static void Pan(const ACameraPawn* PawnRef, const float MinPanY, const float MaxPanY, const float Sensitivity,
// const float CameraX, const float CameraY);
// Makes mouse snap on grid in block increments
// Parameters
// IN float Axis
// IN int GridSize
// OUT float AxisOut
UFUNCTION(Category = FunctionLibrary, BlueprintPure)
static void GridSnap(float Axis, int GridSize, float& AxisOut);
// todo comment
// Parameters
// IN float Delta Seconds
// IN float Time Unit
// IN float Clockwork
// OUT float Clockwork
// OUT int Day Tick
UFUNCTION(Category = FunctionLibrary, BlueprintPure)
static void SetClockwork(float DeltaSeconds, float TimeUnit, float ClockworkIn,
float& ClockworkOut, int& DayTick);
// Returns if Actor is placed on slope terrain
// Parameters
// IN AActor* Actor
// IN FVector Extent
// OUT bool BadLocation
UFUNCTION(Category = FunctionLibrary, BlueprintCallable)
static void CalculateSlope(AActor* Actor, FVector Extent, bool& BadLocation);
// Returns location, forward vector and right vector
// Parameters
// IN AActor* Actor
// OUT FVector ActorLocation
// OUT FVector ForwardVector
// OUT FVector RightVector
UFUNCTION(Category = FunctionLibrary, BlueprintPure)
static void GetVectors(const AActor* Actor, FVector& ActorLocation, FVector& ForwardVector, FVector& RightVector);
// Traces landscape to return difference between mesh and landscape
// Parameters
// IN AActor* Actor
// IN FVector TraceLocation
// OUT float Difference
UFUNCTION(Category = FunctionLibrary, BlueprintCallable)
static void SlopeTrace(const AActor* Actor, FVector TraceLocation, float& Difference);
// Lerps from current location to destination by speed
// Parameters
// IN FVector Current Location (location of actor - Camera pawn)
// IN FVector Destination Location (location of actor - Building, NPC...)
// IN float Speed
// OUT FVector NewLocation
UFUNCTION(Category = FunctionLibrary, BlueprintPure)
static void HUD_LerpLocation(FVector CurrentLocation, FVector DestinationLocation, float Speed,
FVector& NewLocation);
// Sets location of Entrance
// Parameters
// IN USceneComponent* Entrance
// IN Static mesh component* Mesh
UFUNCTION(Category = FunctionLibrary, BlueprintCallable)
static void SetBuildingEntrance(USceneComponent* Entrance, const UStaticMeshComponent* Mesh);
UFUNCTION(Category = FunctionLibrary, BlueprintCallable)
static void SetBuildingCollisionBox(UBoxComponent* Collision, const UStaticMeshComponent* Mesh);
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/EBuildingType.h
|
<filename>TD2020/Source/TD2020/Public/TD2020/Enums/EBuildingType.h<gh_stars>1-10
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "EBuildingType.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class EBuildingType_Enum : uint8
{
Residential UMETA(DisplayName = "Residential"),
Commercial UMETA(DisplayName = "Commercial"),
Industrial UMETA(DisplayName = "Industrial")
};
UCLASS()
class TD2020_API UEBuildingType : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
EBuildingType_Enum BuildingType;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/EResourcesRow.h
|
<reponame>JernejHabjan/TrumpDefense2020
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "EResourcesRow.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class EResourcesRow_Enum : uint8
{
None UMETA(DisplayName = "None"),
Granite UMETA(DisplayName = "Granite")
};
UCLASS()
class TD2020_API UEResourcesRow : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
EResourcesRow_Enum ResourcesRow;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/ELocationType.h
|
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "ELocationType.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class ELocationType_Enum : uint8
{
NoneSelected UMETA(DisplayName = "NoneSelected"),
Home UMETA(DisplayName = "Home"),
Office UMETA(DisplayName = "Office"),
Restaurant UMETA(DisplayName = "Restaurant")
};
UCLASS()
class TD2020_API UELocationType : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
ELocationType_Enum LocationType;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/ENPCNameFemale.h
|
<filename>TD2020/Source/TD2020/Public/TD2020/Enums/ENPCNameFemale.h<gh_stars>1-10
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "ENPCNameFemale.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class ENPCNameFemale_Enum : uint8
{
Ana UMETA(DisplayName = "Ana"),
Anja UMETA(DisplayName = "Anja"),
Nika UMETA(DisplayName = "Nika"),
Ema UMETA(DisplayName = "Ema"),
ENPCNameFemale_MAX UMETA(DisplayName = "MAX"),
};
UCLASS()
class TD2020_API UENPCNameFemale : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
ENPCNameFemale_Enum NPCNameFemale;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/EMonthNames.h
|
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "EMonthNames.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class EMonthNames_Enum : uint8
{
January UMETA(DisplayName = "January"),
February UMETA(DisplayName = "February"),
March UMETA(DisplayName = "March"),
April UMETA(DisplayName = "April"),
May UMETA(DisplayName = "May"),
June UMETA(DisplayName = "June"),
July UMETA(DisplayName = "July"),
August UMETA(DisplayName = "August"),
September UMETA(DisplayName = "September"),
October UMETA(DisplayName = "October"),
November UMETA(DisplayName = "November"),
December UMETA(DisplayName = "December")
};
UCLASS()
class TD2020_API UEMonthNames : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
EMonthNames_Enum MonthNames;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enviroment/Sky/MySkySphere.h
|
<reponame>JernejHabjan/TrumpDefense2020<filename>TD2020/Source/TD2020/Public/TD2020/Enviroment/Sky/MySkySphere.h
// No copyright - copy as you please
#pragma once
#include "GameFramework/Actor.h"
#include "MySkySphere.generated.h"
class USceneComponent;
class UStaticMeshComponent;
struct FLinearColor;
class UMaterialInstanceDynamic;
class ADirectionalLight;
class UCurveLinearColor;
class UMaterial;
class AActor;
UCLASS()
class TD2020_API AMySkySphere : public AActor
{
GENERATED_BODY()
protected:
// Called when the game staTD2020 or when spawned
virtual void BeginPlay() override;
public:
// PROPERTIES
// Sky-dome
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Skydome)
USceneComponent* Scene;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = Skydome)
UStaticMeshComponent* SkySphereMesh;
// Override settings
// If no directional light is assigned, this value determines the height of the sun - Slider range -> -1 to 1
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Override Settings")
float SunHeight;
// Affects the size of the gradient from zenith color to horizon color
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Override Settings")
float HorizonFalloff;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Override Settings")
FLinearColor ZenithColor;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Override Settings")
FLinearColor HorizonColor;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Override Settings")
FLinearColor CloudColor;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Override Settings")
FLinearColor OverallColor;
// Other properties
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UMaterialInstanceDynamic* SkyMaterialInstance;
//Use this to update the sky material after moving a directional light
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool RefreshMaterial;
//Assign your level's directional light actor to this variable to match the sky's sun position and color
UPROPERTY(EditAnywhere, BlueprintReadWrite)
ADirectionalLight* DirectionalLightActor;
//If enabled, sky colors will change according to the sun's position
UPROPERTY(EditAnywhere, BlueprintReadWrite)
bool ColorsDeterminedBySunPosition;
//Brightness multiplier for the sun disk
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float SunBrightness;
//Panning speed for the clouds
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float CloudSpeed;
//Opacity of the panning clouds
UPROPERTY(EditAnywhere, BlueprintReadWrite, BlueprintReadWrite)
float CloudOpacity;
//Multiplier for the brightness of the stars when the sun is below the horizon
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float StarsBrightness;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UCurveLinearColor* HorizonColorCurve;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UCurveLinearColor* ZenithColorCurve;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UCurveLinearColor* CloudColorCurve;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
UMaterial* SkyMaterial;
// FUNCTIONS
// Sets default values for this actor's properties
AMySkySphere();
explicit AMySkySphere(const FObjectInitializer& ObjectInitializer);
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called by DayNightCycle class object
UFUNCTION(Category = SunDirection, BlueprintCallable)
bool UpdateSunDirection();
UFUNCTION(Category = Clouds, BlueprintCallable)
void SetCloudSpeed(float CloudSpeedIn);
// Construction script
virtual void OnConstruction(const FTransform& Transform) override;
private:
// if init is valid
bool Valid;
// FUNCTIONS
// validates if all assets are properly loaded and not null
bool Validate() const;
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/EProximityType.h
|
<filename>TD2020/Source/TD2020/Public/TD2020/Enums/EProximityType.h<gh_stars>1-10
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "EProximityType.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class EProximityType_Enum : uint8
{
None UMETA(DisplayName = "None"),
Mining UMETA(DisplayName = "Mining"),
Farming UMETA(DisplayName = "Farming")
};
UCLASS()
class TD2020_API UEProximityType : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
EProximityType_Enum ProximityType;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/RTS/TD2020AttackableComponent.h
|
<filename>TD2020/Source/TD2020/Public/RTS/TD2020AttackableComponent.h<gh_stars>1-10
#pragma once
#include <Components/ActorComponent.h>
#include "TD2020AttackableComponent.generated.h"
/**
* Allows choosing the actor as target for an attack order.
*/
UCLASS(meta = (BlueprintSpawnableComponent))
class TD2020_API UTD2020AttackableComponent : public UActorComponent
{
GENERATED_BODY()
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/EAIState.h
|
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "EAIState.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class EAIState_Enum : uint8
{
Homeless UMETA(DisplayName = "Homeless"),
Working UMETA(DisplayName = "Working"),
Sleeping UMETA(DisplayName = "Sleeping"),
MoveByCommander UMETA(DisplayName = "MoveByCommander")
};
UCLASS()
class TD2020_API UEAIState : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
EAIState_Enum AIState;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/ENPCSex.h
|
// No copyright - copy as you please
#pragma once
#include <CoreMinimal.h>
#include <Engine/UserDefinedEnum.h>
#include "ENPCSex.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class ENPCSex_Enum : uint8
{
Male UMETA(DisplayName = "Male"),
Female UMETA(DisplayName = "Female")
};
UCLASS()
class TD2020_API UENPCSex : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
ENPCSex_Enum NPCSex;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/ENPCNameMale.h
|
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "ENPCNameMale.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class ENPCNameMale_Enum : uint8
{
Janez UMETA(DisplayName = "Janez"),
Gasper UMETA(DisplayName = "Gasper"),
Miha UMETA(DisplayName = "Miha"),
Boltezar UMETA(DisplayName = "Boltezar"),
ENPCNameMale_MAX UMETA(DisplayName = "MAX"),
};
UCLASS()
class TD2020_API UENPCNameMale : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
ENPCNameMale_Enum NPCNameMale;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/EGameSpeed.h
|
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "EGameSpeed.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class EGameSpeed_Enum : uint8
{
Speed_0 UMETA(DisplayName = "Speed_0"),
Speed_1 UMETA(DisplayName = "Speed_1"),
Speed_2 UMETA(DisplayName = "Speed_2"),
Speed_3 UMETA(DisplayName = "Speed_3"),
Speed_4 UMETA(DisplayName = "Speed_4"),
Speed_5 UMETA(DisplayName = "Speed_5")
};
UCLASS()
class TD2020_API UEGameSpeed : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
EGameSpeed_Enum GameSpeed;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Enums/EOccupationType.h
|
<reponame>JernejHabjan/TrumpDefense2020
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedEnum.h>
#include "EOccupationType.generated.h"
UENUM(BlueprintType) //"BlueprintType" is essential to include
enum class EOccupationType_Enum : uint8
{
Unemployment UMETA(DisplayName = "Unemployment"),
Construction UMETA(DisplayName = "Construction"),
Miner UMETA(DisplayName = "Miner")
};
UCLASS()
class TD2020_API UEOccupationType : public UUserDefinedEnum
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Enum")
EOccupationType_Enum OccupationType;
//Rest of Class Code
};
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/TD2020.h
|
<reponame>JernejHabjan/TrumpDefense2020<filename>TD2020/Source/TD2020/TD2020.h
#pragma once
#include "Logging/LogMacros.h"
/** when you modify this, please note that this information can be saved with instances
* also DefaultEngine.ini [/Script/Engine.CollisionProfile] should match with this list **/
#define COLLISION_LANDSCAPE ECC_GameTraceChannel1
#define COLLISION_BUILDING ECC_GameTraceChannel2
DECLARE_LOG_CATEGORY_EXTERN(LogTD2020, Log, All);
|
JernejHabjan/TrumpDefense2020
|
TD2020/Source/TD2020/Public/TD2020/Structs/Resources_STRUCT.h
|
<gh_stars>1-10
// No copyright - copy as you please
#pragma once
#include <Engine/UserDefinedStruct.h>
#include "TD2020/Enums/EProximityType.h"
#include <Engine/DataTable.h>
#include "Resources_STRUCT.generated.h"
class UTexture2D;
class UStaticMesh;
USTRUCT(BlueprintType)
struct FResources_Struct : public FTableRowBase
{
GENERATED_BODY()
// Resource static mesh reference
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Data")
UStaticMesh* ResourceMesh;
// Thumbnail of resource - picture
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Data")
UTexture2D* ResourcesThumbnail;
// Resource name
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Data")
FString ProperResourceName;
// Proximity type of resource (mining, farming...)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Data")
EProximityType_Enum ProximityType;
// Harvest time of resource (in hours)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Data")
float HarvestTime;
// defaults
explicit FResources_Struct(
UStaticMesh* ResourceMesh = nullptr,
UTexture2D* ResourcesThumbnail = nullptr,
const FString ProperResourceName = TEXT("Resource"),
const EProximityType_Enum ProximityType = EProximityType_Enum::None,
const float HarvestTime = 1.0f
)
{
this->ResourceMesh = ResourceMesh;
this->ResourcesThumbnail = ResourcesThumbnail;
this->ProperResourceName = ProperResourceName;
this->ProximityType = ProximityType;
this->HarvestTime = HarvestTime;
}
};
UCLASS()
class TD2020_API UResources : public UUserDefinedStruct
{
GENERATED_BODY()
};
|
Rogaven/ODX.Networking
|
deps/ODX.Core/ODStringify.h
|
// ODStringify.h
//
// Copyright (c) 2009-2015 <NAME>, AJR
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
/**
* Stringify defines as strings
*
* @example:
* ODStringify(var) produces @"var" string, ODStringifyClass(NSObject) produces
* @"NSObject" string. Unsafe methods does it without any checks. Unwrap for defines.
*/
#define ODStringifyUnsafe(x) @#x
#define ODStringifyUnwrap(x) ODStringifyUnsafe(x)
#define __ODStringifyCheck(x) __unused __typeof (x) __od_str_obj
#define __ODStringifyCheckClass(x) __unused x *__od_str_obj
#if DEBUG == 1
#define ODStringify(obj) ({ __ODStringifyCheck(obj); ODStringifyUnsafe(obj); })
#define ODStringifyClass(cls) ({ __ODStringifyCheckClass(cls); ODStringifyUnsafe(cls); })
#else
#define ODStringify(obj) (ODStringifyUnsafe(obj))
#define ODStringifyClass(cls) (ODStringifyUnsafe(cls))
#endif
/**
* Concatenate defines as strings
*
* @example:
* ODConcat(od_onceToken, __LINE__) produces 'od_onceTokenN' variable,
* where N is number of current line in code.
*/
#define __ODConcat(x, y) x ## y
#define ODConcat(x, y) __ODConcat(x, y)
/** Clang ignore diagnostic messages wrapper */
#define __ODStringifyClangPragmaStage0(x) #x
#define __ODStringifyClangPragmaStage1Ignore(x) __ODStringifyClangPragmaStage0(clang diagnostic ignored x)
#define ODStringifyClangPragmaClangIgnore(x) __ODStringifyClangPragmaStage1Ignore(#x)
/**
* Wraps code with clang ignore directive
* @param type A type of ignored messages
* @param x A wrapped code
* @example ODCompilerIgnorePush(-Wall, x=1/0);
*/
#define ODCompilerIgnore(type, x) \
_Pragma("clang diagnostic push") \
_Pragma(ODStringifyClangPragmaClangIgnore(type)) \
x \
_Pragma("clang diagnostic pop")
/**
* Push clang ignore directive
* @param type A type of ignored messages
* @example ODCompilerIgnorePush(-Wgnu).
*/
#define ODCompilerIgnorePush(type) \
_Pragma("clang diagnostic push") \
_Pragma(ODStringifyClangPragmaClangIgnore(type))
/** Pop current Clang diagnostic message */
#define ODCompilerPop \
_Pragma("clang diagnostic pop")
/** Current file and line (NSString) */
#define ODCurrentFileAndLine (@__FILE__ ":" ODStringifyUnwrap(__LINE__))
|
Rogaven/ODX.Networking
|
deps/ODX.Core/ODDispatch.h
|
<reponame>Rogaven/ODX.Networking
// ODDispatch.h
//
// Copyright (c) 2009-2015 <NAME>, AJR
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if __BLOCKS__
/*!
* @function ODDispatchAsyncInMainThread
*
* @abstract
* Submits a block for asynchronous execution on a main queue.
*
* @param block
* The block to submit to the target dispatch queue. This function performs
* Block_copy() and Block_release() on behalf of callers.
* The result of passing NULL in this parameter is undefined.
*/
NS_INLINE
void ODDispatchAsyncInMainThread(dispatch_block_t block) {
dispatch_async(dispatch_get_main_queue(), block);
}
/*!
* @function ODDispatchAsyncInBackgroundThread
*
* @abstract
* Submits a block for asynchronous execution on a background queue.
*
* @param priority
* Priorities:
* - DISPATCH_QUEUE_PRIORITY_HIGH
* - DISPATCH_QUEUE_PRIORITY_DEFAULT
* - DISPATCH_QUEUE_PRIORITY_LOW
* - DISPATCH_QUEUE_PRIORITY_BACKGROUND
*
* @param block
* The block to submit to the target dispatch queue. This function performs
* Block_copy() and Block_release() on behalf of callers.
* The result of passing NULL in this parameter is undefined.
*/
NS_INLINE
void ODDispatchAsyncInBackgroundThread(dispatch_queue_priority_t priority, dispatch_block_t block) {
dispatch_async(dispatch_get_global_queue(priority, 0), block);
}
/*!
* @function ODDispatchAfterInMainThread
*
* @abstract
* Submits a block for execution on a main queue with delay.
*
* @param delay
* Delay in seconds
*
* @param block
* The block to submit to the target dispatch queue. This function performs
* Block_copy() and Block_release() on behalf of callers.
* The result of passing NULL in this parameter is undefined.
*/
NS_INLINE
void ODDispatchAfterInMainThread(float delay, dispatch_block_t block) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t) (delay * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
}
#import "ODStringify.h"
/*!
* @function ODDispatchOnce
*
* @abstract
* Execute a block once and only once.
*
* @param block
* The block to execute.
*/
#define ODDispatchOnce(block) \
static dispatch_once_t ODConcat(od_onceToken, __LINE__); \
dispatch_once(&ODConcat(od_onceToken, __LINE__), (block));
#endif
|
kitterion/flax
|
src/lua_test_string.h
|
#ifndef SRC_LUA_TEST_STRING_H_
#define SRC_LUA_TEST_STRING_H_
#include <string>
#include <vector>
class LuaTestString {
public:
class TechnologyProxy {
public:
TechnologyProxy(const std::string& name) : name_(name) {}
TechnologyProxy& UnlockRecipe(const std::string& recipe_name) {
unlocked_recipes_.emplace_back(recipe_name);
return *this;
}
const std::string& name() const { return name_; }
const std::vector<std::string> unlocked_recipes() const {
return unlocked_recipes_;
}
private:
std::string name_;
std::vector<std::string> unlocked_recipes_;
};
class RecipeProxy {
public:
RecipeProxy(const std::string name) : name_(name), enabled_(true) {}
RecipeProxy& Disable() {
enabled_ = false;
return *this;
}
RecipeProxy& Enable() {
enabled_ = true;
return *this;
}
const std::string& name() const { return name_; }
bool enabled() const { return enabled_; }
private:
std::string name_;
bool enabled_;
};
TechnologyProxy& Technology(const std::string& name) {
technologies_.emplace_back(name);
return technologies_.back();
}
RecipeProxy& Recipe(const std::string& name) {
recipes_.emplace_back(name);
return recipes_.back();
}
operator std::string() {
std::string result;
result.append("data = {raw = {");
result.append("technology = {");
for (const auto& tech : technologies_) {
result.append(tech.name() + " = {");
result.append("name = \"");
result.append(tech.name());
result.append("\",");
if (!tech.unlocked_recipes().empty()) {
result.append("effects = {");
for (size_t i = 0; i < tech.unlocked_recipes().size(); ++i) {
result.append("[" + std::to_string(i + 1) + "] = {");
result.append("type = \"unlock-recipe\",");
result.append("recipe = \"" + tech.unlocked_recipes()[i] + "\",");
result.append("},");
}
result.append("},");
}
result.append("},");
}
result.append("}, recipe = {");
for (const auto& recipe : recipes_) {
result.append(recipe.name() + " = {");
result.append("name = \"" + recipe.name() + "\",");
result.append("enabled = ");
if (recipe.enabled()) {
result.append("true");
} else {
result.append("false");
}
result.append(",");
result.append("},");
}
result.append("},");
result.append("}}");
return result;
}
private:
std::vector<TechnologyProxy> technologies_;
std::vector<RecipeProxy> recipes_;
};
#endif // SRC_LUA_TEST_STRING_H_
|
kitterion/flax
|
src/lua_data.h
|
#ifndef SRC_LUA_DATA_H_
#define SRC_LUA_DATA_H_
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "sol.hpp"
std::string ToString(const sol::object& obj);
struct Ingredient {
std::string item;
int amount;
};
struct Recipe {
std::vector<Ingredient> inputs;
std::vector<Ingredient> outputs;
std::string id;
bool enabled;
};
struct Technology {
std::string id;
std::vector<std::string> unlocked_recipes;
};
class TechnologyTree {
public:
void Load(const sol::object& obj);
const auto& technologies() const { return technologies_; }
private:
std::unordered_map<std::string, std::unique_ptr<Technology>> technologies_;
};
class LuaData {
public:
bool Load(const std::string& factorio_path);
// Useful for tests.
bool LoadFromString(const std::string& lua_code);
std::vector<const Recipe*> GetEnabledRecipes() const;
private:
void EnableRecipesUnlockedFromTechnology();
void LoadRecipes(const sol::object& obj);
std::unordered_map<std::string, std::unique_ptr<Recipe>> recipes_;
TechnologyTree technology_tree_;
};
#endif // SRC_LUA_DATA_H_
|
rtokarev/m3ufs2
|
m3ufs2.h
|
<filename>m3ufs2.h<gh_stars>1-10
#ifndef _M3UFS2_H_
#define _M3UFS2_H_
/*
* Copyright (c) 2011 <NAME> <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY 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 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.
*/
#include <dirent.h>
#include <features.h>
#include <sys/syscall.h>
#include <unistd.h>
#ifndef __USE_ATFILE
#include <fcntl.h>
#include <stdarg.h>
int openat(int dirfd, const char *pathname, int flags, ...)
{
va_list ap;
mode_t mode = 0000;
if (flags & O_CREAT) {
va_start(ap, flags);
mode = va_arg(ap, mode_t);
va_end(ap);
}
return syscall(__NR_openat, dirfd, pathname, flags, mode);
}
int fstatat(int dirfd, const char *pathname, struct stat *buf, int flags)
{
return syscall(__NR_fstatat64, dirfd, pathname, buf, flags);
}
#endif // __USE_ATFILE
struct linux_dirent {
unsigned long d_ino; /* Inode number */
unsigned long d_off; /* Offset to next linux_dirent */
unsigned short d_reclen; /* Length of this linux_dirent */
char d_name[]; /* Filename (null-terminated) */
/* length is actually (d_reclen - 2 -
offsetof(struct linux_dirent, d_name) */
};
int getdents(unsigned int fd, struct linux_dirent *dirp, unsigned int count)
{
return syscall(__NR_getdents, fd, dirp, count);
}
#endif // _M3UFS2_H_
|
rtokarev/m3ufs2
|
m3ufs2.c
|
/*
* Copyright (c) 2011 <NAME> <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the author nor the names of any co-contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY 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 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.
*/
#define FUSE_USE_VERSION 26
#include <m3ufs2.h>
#include <ctype.h>
#include <errno.h>
#include <fuse.h>
#include <limits.h>
#include <pthread.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define EXTM3U "#EXTM3U"
#define EXTINF "#EXTINF:"
#define SWAP(a, b) ({ \
__typeof__(*(a)) t; \
\
t = *b; \
*b = *a; \
*a = t; \
})
#define IS_M3U(path) ({ \
char *ext; \
bool is_m3u = false; \
\
ext = strrchr(path, '.'); \
if (ext != NULL && \
(strcmp(ext, ".m3u") == 0 || strcmp(ext, ".M3U") == 0)) \
is_m3u = true; \
\
is_m3u; \
})
#define RPATH(path) ({ \
const char *rpath = path; \
\
while ((++rpath)[0] == '/'); \
if (rpath[0] == '\0') \
rpath = "."; \
\
rpath; \
})
struct m3ufs2 {
char *dir;
int dirfd;
char *mountpoint;
int shuffle;
};
struct m3u_entry {
char *name;
char *path;
};
struct m3u {
char *fname;
time_t mtime;
struct m3u_entry *entry;
uint32_t size;
uint32_t len;
uint32_t count_order;
struct m3u *next;
};
enum {
KEY_HELP,
KEY_VERSION
};
static struct m3ufs2 m3ufs2;
#define M3UFS2_OPT(t, p, v) {t, offsetof(struct m3ufs2, p), v }
static struct fuse_opt m3ufs2_opts[] = {
M3UFS2_OPT("shuffle", shuffle, 1),
FUSE_OPT_KEY("-h", KEY_HELP),
FUSE_OPT_KEY("--help", KEY_HELP),
FUSE_OPT_KEY("-V", KEY_VERSION),
FUSE_OPT_KEY("--version", KEY_VERSION),
FUSE_OPT_END
};
static pthread_mutex_t m3u_mutex = PTHREAD_MUTEX_INITIALIZER;
static struct m3u *m3u = NULL;
static void m3u_free(struct m3u *m)
{
unsigned i;
struct m3u_entry *entry;
for (i = 0, entry = m->entry; i < m->len; i++, entry++) {
if (entry->path != NULL)
free(entry->path);
if (entry->name != NULL)
free(entry->name);
}
if (m->fname != NULL)
free(m->fname);
if (m->entry != NULL)
free(m->entry);
free(m);
}
static void close_(int *fd)
{
if (*fd != -1)
close(*fd);
}
static void fclose_(FILE **f)
{
if (*f != NULL)
fclose(*f);
}
static void m3u_free_(struct m3u **m)
{
if (*m == NULL)
return;
m3u_free(*m);
}
static void str_free_(char **str)
{
if (*str == NULL)
return;
free(*str);
}
static uint32_t num_order(uint32_t num)
{
uint32_t order = 1;
while ((num /= 10) != 0) order++;
return order;
}
#define M3U_ENTRY_ALLOC_BY 8
static struct m3u *m3u_process(const char *path)
{
struct stat stbuf;
int fd __attribute__((cleanup(close_))) = -1;
FILE *f __attribute__((cleanup(fclose_))) = NULL;
const char *rpath;
char *dir, *c;
struct m3u *m __attribute__((cleanup(m3u_free_))) = NULL;
char *line __attribute__((cleanup(str_free_))) = NULL;
size_t line_size = 0;
char *firstline = NULL;
bool is_extm3u = false;
char *extinf_name __attribute__((cleanup(str_free_))) = NULL;
m = calloc(1, sizeof(*m));
if (m == NULL)
return NULL;
m->fname = strdup(path);
if (m->fname == NULL)
return NULL;
rpath = RPATH(path);
c = strrchr(path, '/');
dir = strndupa(path, c - path + 1);
if (fstatat(m3ufs2.dirfd, rpath, &stbuf, 0) != 0)
return NULL;
m->mtime = stbuf.st_mtime;
fd = openat(m3ufs2.dirfd, rpath, O_RDONLY);
if (fd == -1)
return NULL;
f = fdopen(fd, "r");
if (f == NULL)
return NULL;
fd = -1;
errno = 0;
while (getline(&line, &line_size, f) != -1) {
struct m3u_entry *entry;
char str[PATH_MAX];
char *fname;
line[strlen(line) - 1] = '\0';
// Skip leading white space.
for (fname = line; *fname != '\0' && isspace(*fname) != 0; fname++);
if (firstline == NULL) {
// Check for extended M3U format.
firstline = line;
if (strncmp(firstline, EXTM3U, sizeof(EXTM3U) - 1) == 0) {
is_extm3u = true;
continue;
}
}
if (is_extm3u == true &&
strncmp(line, EXTINF, sizeof(EXTINF) - 1) == 0) {
c = strchr(line, ',');
if (c != NULL) {
while (isspace(*(++c)) != 0);
if (extinf_name != NULL)
free(extinf_name);
extinf_name = strdup(c);
}
continue;
}
// Skip empty lines and comments.
if (fname[0] == '\0' || fname[0] == '#')
continue;
// Skip absolute path.
if (fname[0] == '/')
continue;
if (m->len == m->size) {
struct m3u_entry *new_entry;
m->size += M3U_ENTRY_ALLOC_BY;
new_entry = realloc(m->entry, m->size * sizeof(*entry));
if (new_entry == NULL)
return NULL;
m->entry = new_entry;
}
entry = &m->entry[m->len++];
memset(entry, 0, sizeof(*entry));
snprintf(str, sizeof(str), "%s%s", dir, fname);
entry->path = strdup(str);
if (entry->path == NULL)
return NULL;
if (extinf_name != NULL) {
entry->name = extinf_name;
extinf_name = NULL;
continue;
}
c = strrchr(fname, '/');
if (c != NULL)
c++;
else
c = fname;
entry->name = strdup(c);
if (entry->name == NULL)
return NULL;
};
if (errno != 0)
return NULL;
m->count_order = num_order(m->len);
m->next = m3u;
m3u = m;
m = NULL;
return m3u;
}
static void m3u_unlock_(pthread_mutex_t **mutex)
{
if (*mutex == NULL)
return;
pthread_mutex_unlock(*mutex);
}
static pthread_mutex_t *m3u_lock(void)
{
if (pthread_mutex_lock(&m3u_mutex) != 0)
return NULL;
return &m3u_mutex;
}
static struct m3u *m3u_lookup(const char *path)
{
pthread_mutex_t *mutex __attribute__((cleanup(m3u_unlock_))) = NULL;
mutex = m3u_lock();
if (mutex == NULL)
return NULL;
for (struct m3u *m = m3u, *m_prev = NULL; m != NULL; m_prev = m, m = m->next) {
const char *rpath;
struct stat stbuf;
if (strcmp(m3u->fname, path) != 0)
continue;
rpath = RPATH(path);
if (fstatat(m3ufs2.dirfd, rpath, &stbuf, 0) != 0)
return NULL;
if (stbuf.st_mtime == m->mtime)
return m;
// We are to update.
if (m_prev != NULL)
m_prev->next = m->next;
else
m3u = m->next;
m3u_free(m);
break;
}
return m3u_process(path);;
}
static struct m3u *is_m3u_entry(const char *path)
{
char *dir;
char *c;
c = strrchr(path, '/');
dir = strndupa(path, c - path);
if (IS_M3U(dir) == true)
return m3u_lookup(dir);
return NULL;
}
static struct m3u_entry *m3u_entry_lookup(struct m3u *m, const char *name)
{
pthread_mutex_t *mutex __attribute__((cleanup(m3u_unlock_))) = NULL;
char *endptr = NULL;
uint32_t num;
mutex = m3u_lock();
if (mutex == NULL)
return NULL;
num = strtoul(name, &endptr, 10);
if (endptr == NULL || strncmp(endptr, ". ", 2) != 0)
return NULL;
name = endptr + 2;
if (num > m->len ||
strcmp(name, m->entry[num - 1].name) != 0)
return NULL;
return &m->entry[num - 1];
}
static void m3u_shuffle(struct m3u *m)
{
pthread_mutex_t *mutex __attribute__((cleanup(m3u_unlock_))) = NULL;
uint32_t len = m->len;
mutex = m3u_lock();
if (mutex == NULL)
return;
while (len != 0) {
uint32_t i;
i = rand() % (len--);
SWAP(&m->entry[i], &m->entry[len]);
}
}
static int m3ufs2_getattr(const char *path, struct stat *stbuf)
{
const char *rpath;
struct m3u *m;
if (path[0] != '/')
return -ENOENT;
m = is_m3u_entry(path);
if (m != NULL) {
struct m3u_entry *entry;
char *entry_name;
entry_name = strrchr(path, '/') + 1;
entry = m3u_entry_lookup(m, entry_name);
if (entry == NULL)
return -ENOENT;
return m3ufs2_getattr(entry->path, stbuf);
}
rpath = RPATH(path);
if (fstatat(m3ufs2.dirfd, rpath, stbuf, 0) != 0)
return -errno;
if (IS_M3U(path) == true) {
stbuf->st_mode &= ~S_IFREG;
stbuf->st_mode |= S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
}
return 0;
}
#define DIRENT_READAHEAD_SIZE 1024
static int m3ufs2_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset __attribute__((unused)),
struct fuse_file_info *fi __attribute__((unused)))
{
const char *rpath;
int dirfd __attribute__((cleanup(close_))) = -1;
if (path[0] != '/')
return -ENOENT;
if (IS_M3U(path) == true) {
struct m3u *m;
unsigned i;
struct m3u_entry *entry;
errno = 0;
m = m3u_lookup(path);
if (m == NULL) {
if (errno == 0)
return -ENOENT;
return -errno;
}
if (m3ufs2.shuffle != 0)
m3u_shuffle(m);
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
for (i = 0, entry = m->entry; i < m->len; i++, entry++) {
struct stat stbuf;
char name[PATH_MAX];
if (m3ufs2_getattr(entry->path, &stbuf) != 0) {
if (errno != ENOENT)
return -errno;
continue;
}
snprintf(name, sizeof(name), "%.*u. %s",
m->count_order, i + 1, entry->name);
filler(buf, name, &stbuf, 0);
}
return 0;
}
rpath = RPATH(path);
dirfd = openat(m3ufs2.dirfd, rpath, O_DIRECTORY | O_RDONLY);
if (dirfd == -1)
return -errno;
do {
char dirent_buf[DIRENT_READAHEAD_SIZE];
int count;
count = getdents(dirfd, (struct linux_dirent *)dirent_buf,
DIRENT_READAHEAD_SIZE);
if (count < 0)
return count;
if (count == 0)
return 0;
for (struct linux_dirent *d = (struct linux_dirent *)dirent_buf;
(char *)d < dirent_buf + count;
d = (struct linux_dirent *)((char *)d + d->d_reclen)) {
char epath[PATH_MAX];
struct stat stbuf;
snprintf(epath, sizeof(epath), "%s/%s", path, d->d_name);
if (m3ufs2_getattr(epath, &stbuf) != 0)
return -errno;
filler(buf, d->d_name, &stbuf, 0);
};
} while (1);
return 0;
}
static int m3ufs2_open(const char *path, struct fuse_file_info *fi)
{
const char *rpath;
struct m3u *m;
if (path[0] != '/')
return -ENOENT;
m = is_m3u_entry(path);
if (m != NULL) {
struct m3u_entry *entry;
char *entry_name;
entry_name = strrchr(path, '/') + 1;
entry = m3u_entry_lookup(m, entry_name);
if (entry == NULL)
return -ENOENT;
return m3ufs2_open(entry->path, fi);
}
rpath = RPATH(path);
fi->fh = openat(m3ufs2.dirfd, rpath, O_RDONLY);
if ((int)fi->fh == -1)
return -errno;
return 0;
}
static int m3ufs2_read(const char *path __attribute__((unused)),
char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
return pread(fi->fh, buf, size, offset);
}
static int m3ufs2_release(const char *path __attribute__((unused)), struct fuse_file_info *fi)
{
if (close(fi->fh) != 0)
return -errno;
return 0;
}
static struct fuse_operations m3ufs2_op = {
.getattr = m3ufs2_getattr,
.readdir = m3ufs2_readdir,
.open = m3ufs2_open,
.read = m3ufs2_read,
.release = m3ufs2_release
};
static void usage(const char *progname)
{
printf("usage: %s dir mountpoint [options]\n"
"\n"
"general options:\n"
" -o opt,[opt...] mount options\n"
" -h --help print help\n"
" -V --version print version\n"
"\n"
"M3UFS2 options:\n"
" -o shuffle shuffle playlist\n"
"\n",
progname);
}
#define OPT_MAX 256
static int m3ufs2_opt_proc(void *data, const char *arg, int key,
struct fuse_args *outargs __attribute__((unused)))
{
struct m3ufs2 *m3ufs2 = data;
switch (key) {
case FUSE_OPT_KEY_NONOPT:
if (m3ufs2->dir == NULL)
m3ufs2->dir = strdup(arg);
else if (m3ufs2->mountpoint == NULL) {
m3ufs2->mountpoint = strdup(arg);
fuse_opt_add_arg(outargs, arg);
} else {
fprintf(stderr, "invalid options\n");
exit(EXIT_FAILURE);
}
return 0;
case FUSE_OPT_KEY_OPT: {
char opt[OPT_MAX];
snprintf(opt, sizeof(opt), "-o%s", arg);
fuse_opt_add_arg(outargs, opt);
return 0;
}
case KEY_HELP:
usage(outargs->argv[0]);
fuse_opt_add_arg(outargs, "-ho");
fuse_main(outargs->argc, outargs->argv, &m3ufs2_op, NULL);
exit(EXIT_SUCCESS);
case KEY_VERSION:
printf("M3UFS2 version: %s\n", VERSION);
fuse_opt_add_arg(outargs, "--version");
fuse_main(outargs->argc, outargs->argv, &m3ufs2_op, NULL);
exit(EXIT_SUCCESS);
default:
fprintf(stderr, "internal error\n");
exit(EXIT_FAILURE);
}
return 0;
}
int main(int argc, char *argv[])
{
struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
char real_dir[PATH_MAX], real_mountpoint[PATH_MAX];
if (fuse_opt_parse(&args, &m3ufs2, m3ufs2_opts, m3ufs2_opt_proc) != 0)
exit(EXIT_FAILURE);
if (realpath(m3ufs2.dir, real_dir) == NULL) {
fprintf(stderr, "bad dir `%s': %m\n", m3ufs2.dir);
exit(EXIT_FAILURE);
}
if (realpath(m3ufs2.mountpoint, real_mountpoint) == NULL) {
fprintf(stderr, "bad mountpoint `%s': %m\n", m3ufs2.mountpoint);
exit(EXIT_FAILURE);
}
if (strcmp(real_dir, real_mountpoint) == 0)
fuse_opt_add_arg(&args, "-ononempty");
m3ufs2.dirfd = open(m3ufs2.dir, O_DIRECTORY | O_RDONLY);
if (m3ufs2.dirfd == -1)
exit(EXIT_FAILURE);
return fuse_main(args.argc, args.argv, &m3ufs2_op, NULL);
}
|
apfeltee/optparse
|
test.c
|
<reponame>apfeltee/optparse<filename>test.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "optparse.h"
/*
./a.out foo bar -I/usr/include quux --load=foo.dll -Ic:/blah/include dorks --load
include: </usr/include>
loading <foo.dll>
include: <c:/blah/include>
error: --load needs an argument
positional args:
nargv[0] = "foo"
nargv[1] = "bar"
nargv[2] = "quux"
nargv[3] = "dorks"
===========================
./a.out foo bar -I/usr/include quux -- --load=foo.dll -Ic:/blah/include dorks --load
include: </usr/include>
positional args:
nargv[0] = "foo"
nargv[1] = "bar"
nargv[2] = "quux"
nargv[3] = "--load=foo.dll"
nargv[4] = "-Ic:/blah/include"
nargv[5] = "dorks"
nargv[6] = "--load"
*/
void print_help(const char* arg0)
{
printf("help for %s goes here\n", arg0);
}
int main(int argc, char** argv)
{
optparser_t prs;
int i;
int c;
char* fopt;
char* fval;
bool pretty;
bool finished;
(void)pretty;
finished = false;
pretty = false;
optparse_init(&prs, argc, argv, 1, 255, 255);
while(!finished)
{
if((c = optparse_parse(&prs, &fopt, &fval)) == -1)
{
break;
}
if(c != 0)
{
switch(c)
{
/* handle long options: */
case 1:
{
if(strcmp(fopt, "--help") == 0)
{
print_help(argv[0]);
return 0;
}
else if(strcmp(fopt, "--load") == 0)
{
if(fval != NULL)
{
printf("loading <%s>\n", fval);
}
else
{
printf("error: --load needs an argument\n");
}
}
else
{
printf("error: unrecognized long option '%s'\n", fopt);
}
}
break;
/* handle short options */
case 'h':
print_help(argv[0]);
finished = true;
break;
case 'p':
printf("will prettyfy\n");
pretty = true;
break;
case 'v':
printf("verbose mode\n");
break;
case 'I':
if(fval != NULL)
{
printf("include: <%s>\n", fval);
}
else
{
printf("error: option '-I' needs a value\n");
}
break;
default:
fprintf(stderr, "unrecognized option '-%c'\n", c);
return 1;
break;
}
}
}
if(prs.nargc > 0)
{
printf("positional args:\n");
for(i=0; i<prs.nargc; i++)
{
printf("nargv[%d] = \"%s\"\n", i, prs.nargv[i]);
}
}
optparse_finish(&prs);
return 0;
}
|
apfeltee/optparse
|
optparse.h
|
#pragma once
/*
* copyright 2021-.... github.com/apfeltee
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
/**
*
* sample usage:
*
int main(int argc, char* argv[])
...
optparser_t prs;
// for now, optparser focuses on switches, i.e., boolean values.
bool mything;
// first, initiate the parser.
// see the comments for optparse_init for the meaning of the arguments here.
optparse_init(&prs, argc, argv, 1, 255, 255);
// now, loop through the args with optparse_parse():
while(true)
{
int c;
// -1 means either finished parsing, or an error occured.
// the latter is fairly unlikely, and optparser will internally
// terminate, since an error here is not expected to be recovered from.
if((c = optparse_parse(&prs)) == -1)
{
break;
}
// if c is 0, then it's a positional argument, and not an option!
if(c != 0)
{
switch(c)
{
case 't':
mything = true;
break;
// handling unexpected options in plain C style.
default:
// do something about an unexpected option
break;
}
}
}
// now, prs.nargc is the count of positional arguments.
// they start at 0.
// prs.nargv is the array of positional args.
for(i=0; i<prs.nargc; i++)
{
char* arg = prs.nargv[i];
...
}
// finally, cleanup.
optparse_finish(&prs);
}
*/
typedef struct optparser_t optparser_t;
struct optparser_t
{
/* used in optparse_parse to track the current index */
int track;
/* the most amount of positional args to store */
int maxargv;
/* the longest a positional argument can be */
int maxlen;
/* new argc - i.e., how many positional elements are available */
int nargc;
/* new argv - i.e., positional arguments */
char** nargv;
/* the original argc, as passed to main*/
int oargc;
/* the original argv, as passed to main */
char** oargv;
/* when encountering "--", then parsing is stopped, and all remainder is just appended to nargv */
bool stopparsing;
/* if an error occured, this is the index at which the error occured.*/
int unparsedidx;
};
/**
* initiate the parser.
* returns true, if initialization was successful, false otherwise.
*
* @param argc
* the argc param as passed to main().
*
* @param argv
* the argv param as passed to main().
*
* @param begin
* the first index to argc for parsing. normally, it should be 1.
*
* @param maxargv
* how many positional arguments to preallocate?
* reasonable value is somewhere between 128 - 1024.
*
* @param maxlen
* the longest a positional argument may be.
* since this needs to be malloc'd, a reasonable value is 256.
*
*/
static bool optparse_init(optparser_t* prs, int argc, char** argv, int begin, size_t maxargv, size_t maxlen)
{
prs->nargc = 0;
prs->track = begin;
prs->oargc = argc;
prs->oargv = argv;
prs->maxargv = maxargv;
prs->maxlen = maxlen;
prs->unparsedidx = 0;
prs->stopparsing = false;
/* prevent memory read errors by allocating one additional element. */
prs->nargv = (char**)malloc(prs->maxargv + 1);
if(prs->nargv == NULL)
{
return false;
}
return true;
}
/**
* the actual parser.
*
* the return value depends on what it encounters:
*
* 0: a positional argument, which is appended to nargv.
* -1: end of argv, or an error occured. either way, this value marks exiting the loop.
* 1: a long option. full option will be stored in $fullopt.
* 2..256: a short option. for example, if argv[n] is "-p", then the return value is 'p' (decimal 112).
*
* if argv[n] is "--", then future parsing is disabled; this is what getopt() (and similar libs) does.
* so, argv[]={"foo", "-p", "bar", "--", "quux", "-f", "-d"} would result in
* optparse_parse() returning {0, 'p', 0, 0, 0, 0, 0, -1}, and
* nargv being {"foo", "bar", "quux", "-f", "-d"}.
* the string "--" is never included, obviously.
*
*
* @param islong
* will be set to true if the argument is a long option, i.e., "--foo".
* that's all it does for now; actual long parsing isn't included (yet!)
*/
static int optparse_parse(optparser_t* prs, char** fullopt, char** optval)
{
/*
* length was chosen by fair dice roll.
* guaranteed to theoretically be long enough to contain even unreasonably long options,
* like those used by LLVM utilities.
* potentially too short for options like inclusion opts...
* (-Iz:/dev/foo/bar/baz/quux/.../stuff/things/frobwise/threeth/...)
*/
enum{ kScratchpadLength = (1024 * 2) };
int i;
int vend;
int slen;
char* tmp;
char* arg;
/*
* where the string for long options is temporarily stored.
*/
static char scratchpad[kScratchpadLength + 1];
*fullopt = NULL;
*optval = NULL;
if((prs->track >= prs->oargc) || (prs->track >= prs->maxargv))
{
prs->unparsedidx = prs->track;
return -1;
}
arg = prs->oargv[prs->track];
slen = (int)strlen(arg);
*fullopt = arg;
prs->track++;
if((prs->stopparsing == false) && (arg[0] == '-'))
{
if(arg[1] == '-')
{
if(arg[2] == 0)
{
/* encountered '--', meaning to stop processing arguments */
prs->stopparsing = true;
return 0;
}
else
{
/* reset scratchpad */
memset(scratchpad, 0, kScratchpadLength);
/* is there a value attached? */
if((tmp = strchr(arg, '=')) != NULL)
{
/* there's a value, something like "--foo=bar" */
for(i=0; i<slen; i++)
{
if(arg[i] == '=')
{
vend = i;
break;
}
}
/*
* the full option is: $lengthOfArgument - ($whereEqualSignAppears + 2)
* so, with "--foo=bar":
* $lengthOfArgument=9
* $whereEqualSignAppears=5
*
*/
memcpy(scratchpad, arg, slen - (vend + 2));
*fullopt = scratchpad;
*optval = (arg + (vend + 1));
}
return 1;
}
}
else
{
/*
* for short options, the value is just the string minus "-" and the opt char.
* in cling:
* [cling]$ std::cout << ("-I/foo" + 2) << std::endl;
* /foo
*/
if(arg[2] != 0)
{
*optval = (arg + 2);
}
return arg[1];
}
}
else
{
prs->nargv[prs->nargc] = (char*)malloc(prs->maxlen + 1);
memset(prs->nargv[prs->nargc], 0, prs->maxlen);
memcpy(prs->nargv[prs->nargc], arg, strlen(arg));
prs->nargc++;
}
return 0;
}
/**
* deallocate positional args, and nargv.
*/
static void optparse_finish(optparser_t* prs)
{
int i;
for(i=0; i<prs->nargc; i++)
{
free(prs->nargv[i]);
prs->nargv[i] = NULL;
}
free(prs->nargv);
}
|
Hurtubise-Epic/FaceflowApp
|
Plugins/FaceflowLive/Source/FaceflowLive/Public/FaceflowLiveSource.h
|
<reponame>Hurtubise-Epic/FaceflowApp
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "ILiveLinkSource.h"
#include "HAL/Runnable.h"
#include "HAL/ThreadSafeBool.h"
#include "IMessageContext.h"
#include "Interfaces/IPv4/IPv4Endpoint.h"
class FRunnableThread;
class FSocket;
class ILiveLinkClient;
class ISocketSubsystem;
class FSocketIONative;
class FACEFLOWLIVE_API FFaceflowLiveSource : public ILiveLinkSource, public FRunnable
{
public:
FFaceflowLiveSource(FIPv4Endpoint Endpoint);
virtual ~FFaceflowLiveSource();
// Begin ILiveLinkSource Interface
virtual void ReceiveClient(ILiveLinkClient* InClient, FGuid InSourceGuid) override;
virtual bool IsSourceStillValid() const override;
virtual bool RequestSourceShutdown() override;
virtual FText GetSourceType() const override { return SourceType; };
virtual FText GetSourceMachineName() const override { return SourceMachineName; }
virtual FText GetSourceStatus() const override { return SourceStatus; }
// End ILiveLinkSource Interface
// Begin FRunnable Interface
virtual bool Init() override { return true; }
virtual uint32 Run() override;
void Start();
virtual void Stop() override;
virtual void Exit() override { }
// End FRunnable Interface
void HandleReceivedData(TSharedPtr<TArray<uint8>, ESPMode::ThreadSafe> ReceivedData);
/**
* Request a new plugin scoped pointer as a shared ptr.
*/
virtual TSharedPtr<FSocketIONative> NewValidNativePointer() { return nullptr; };
/**
* Request a shared FSocketIONative instance for a given id. May allocate a new pointer.
*/
virtual TSharedPtr<FSocketIONative> ValidSharedNativePointer(FString SharedId) { return nullptr; };
/**
* Releases the given plugin scoped pointer using a background thread
* After calling this function make sure to set your pointer to nullptr.
*/
virtual void ReleaseNativePointer(TSharedPtr<FSocketIONative> PointerToRelease) {};
private:
ILiveLinkClient* Client;
// Our identifier in LiveLink
FGuid SourceGuid;
FMessageAddress ConnectionAddress;
FText SourceType;
FText SourceMachineName;
FText SourceStatus;
FIPv4Endpoint DeviceEndpoint;
// Socket to receive data on
FSocket* Socket;
// Subsystem associated to Socket
ISocketSubsystem* SocketSubsystem;
// Threadsafe Bool for terminating the main thread loop
FThreadSafeBool Stopping;
// Thread to run socket operations on
FRunnableThread* Thread;
// Name of the sockets thread
FString ThreadName;
// Time to wait between attempted receives
FTimespan WaitTime;
// List of subjects we've already encountered
TSet<FName> EncounteredSubjects;
// Buffer to receive socket data into
TArray<uint8> RecvBuffer;
};
|
Hurtubise-Epic/FaceflowApp
|
Plugins/FaceflowLive/Source/FaceflowLive/Private/SFaceflowLiveSourceFactory.h
|
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Widgets/SCompoundWidget.h"
#include "Input/Reply.h"
#include "Types/SlateEnums.h"
#include "Widgets/DeclarativeSyntaxSupport.h"
class SEditableTextBox;
class SFaceflowLiveSourceFactory : public SCompoundWidget
{
public:
DECLARE_DELEGATE_OneParam(FOnOkClicked, FIPv4Endpoint);
SLATE_BEGIN_ARGS(SFaceflowLiveSourceFactory){}
SLATE_EVENT(FOnOkClicked, OnOkClicked)
SLATE_END_ARGS()
void Construct(const FArguments& Args);
private:
void OnEndpointChanged(const FText& NewValue, ETextCommit::Type);
FReply OnOkClicked();
TWeakPtr<SEditableTextBox> EditabledText;
FOnOkClicked OkClicked;
};
|
clayne/RGB2Y
|
RGB2Y.h
|
<reponame>clayne/RGB2Y
/*******************************************************************
* RGB2Y.h
* RGB2Y
*
* Author: <NAME>
* <EMAIL>
* https://github.com/komrad36
*
* Last updated Sep 29, 2018
*******************************************************************/
//
// Fastest CPU (AVX/SSE) implementation of RGB to grayscale.
// Roughly 3x faster than OpenCV's implementation with AVX2, or 2x faster
// than OpenCV's implementation if using SSE only.
//
// Converts an RGB color image to grayscale.
//
// You can use equal weighting by calling the templated
// function with weight set to 'false', or you
// can specify non-equal weights (only slightly slower).
//
// The default non-equal weights match OpenCV's default.
//
// For even more speed see the CUDA version:
// github.com/komrad36/CUDARGB2Y
//
// If you do not have AVX2, uncomment the #define NO_AVX_PLEASE below to
// use only SSE isntructions. NOTE THAT THIS IS ABOUT 50% SLOWER.
// A processor with full AVX2 support is highly recommended.
//
// All functionality is contained in RGB2Y.h.
// 'main.cpp' is a demo and test harness.
//
#pragma once
//#define NO_AVX_PLEASE
// Set your weights here.
constexpr double B_WEIGHT = 0.114;
constexpr double G_WEIGHT = 0.587;
constexpr double R_WEIGHT = 0.299;
#include <algorithm>
#include <cstdint>
#include <future>
#include <immintrin.h>
// Internal; do NOT modify
constexpr uint16_t B_WT = static_cast<uint16_t>(32768.0 * B_WEIGHT + 0.5);
constexpr uint16_t G_WT = static_cast<uint16_t>(32768.0 * G_WEIGHT + 0.5);
constexpr uint16_t R_WT = static_cast<uint16_t>(32768.0 * R_WEIGHT + 0.5);
static const __m256i weight_vec = _mm256_setr_epi16(B_WT, G_WT, R_WT, B_WT, G_WT, R_WT, B_WT, G_WT, R_WT, B_WT, G_WT, R_WT, B_WT, G_WT, R_WT, B_WT);
template<bool weight>
void RGB2Y_ref(const uint8_t* __restrict const data, const int32_t cols, const int32_t rows, const int32_t stride, uint8_t* const __restrict out) {
if (!weight) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
const auto idx = 3 * (i*stride + j);
out[i*stride + j] = (static_cast<uint32_t>(data[idx]) + static_cast<uint32_t>(data[idx + 1]) + static_cast<uint32_t>(data[idx + 2]) + 1) / 3;
}
}
}
else {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
const auto idx = 3 * (i*stride + j);
out[i*stride + j] = uint8_t(B_WEIGHT * data[idx] + 0.5f) + uint8_t(G_WEIGHT * data[idx + 1] + 0.5f) + uint8_t(R_WEIGHT * data[idx + 2] + 0.5f);
}
}
}
}
template<bool last_row_and_col, bool weight>
void process(const uint8_t* __restrict const pt, const int32_t cols_minus_j, uint8_t* const __restrict out) {
__m128i h3;
if (weight) {
__m256i in1 = _mm256_mulhrs_epi16(_mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i*)(pt))), weight_vec);
__m256i in2 = _mm256_mulhrs_epi16(_mm256_cvtepu8_epi16(_mm_loadu_si128((const __m128i*)(pt + 15))), weight_vec);
__m256i mul = _mm256_packus_epi16(in1, in2);
__m256i b1 = _mm256_shuffle_epi8(mul, _mm256_setr_epi8(0, 3, 6, -1, -1, -1, 11, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 4, 7, -1, -1, 9, 12, -1, -1, -1, -1, -1, -1));
__m256i g1 = _mm256_shuffle_epi8(mul, _mm256_setr_epi8(1, 4, 7, -1, -1, 9, 12, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, 5, -1, -1, -1, 10, 13, -1, -1, -1, -1, -1, -1));
__m256i r1 = _mm256_shuffle_epi8(mul, _mm256_setr_epi8(2, 5, -1, -1, -1, 10, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 3, 6, -1, -1, 8, 11, 14, -1, -1, -1, -1, -1, -1));
__m256i accum = _mm256_adds_epu8(r1, _mm256_adds_epu8(b1, g1));
h3 = _mm_adds_epu8(_mm256_castsi256_si128(accum), _mm256_extracti128_si256(accum, 1));
}
else {
__m256i in1 = _mm256_castsi128_si256(_mm_loadu_si128((const __m128i*)(pt)));
in1 = _mm256_inserti128_si256(in1, _mm_loadu_si128((const __m128i*)(pt + 15)), 1);
__m256i b1 = _mm256_shuffle_epi8(in1, _mm256_setr_epi8(0, -1, 3, -1, 6, -1, 9, -1, 12, -1, -1, -1, -1, -1, -1, -1, 0, -1, 3, -1, 6, -1, 9, -1, 12, -1, -1, -1, -1, -1, -1, -1));
__m256i g1 = _mm256_shuffle_epi8(in1, _mm256_setr_epi8(1, -1, 4, -1, 7, -1, 10, -1, 13, -1, -1, -1, -1, -1, -1, -1, 1, -1, 4, -1, 7, -1, 10, -1, 13, -1, -1, -1, -1, -1, -1, -1));
__m256i r1 = _mm256_shuffle_epi8(in1, _mm256_setr_epi8(2, -1, 5, -1, 8, -1, 11, -1, 14, -1, -1, -1, -1, -1, -1, -1, 2, -1, 5, -1, 8, -1, 11, -1, 14, -1, -1, -1, -1, -1, -1, -1));
__m256i sum = _mm256_adds_epu16(r1, _mm256_adds_epu16(b1, g1));
__m256i accum = _mm256_mulhrs_epi16(sum, _mm256_set1_epi16(10923));
__m256i shuf = _mm256_shuffle_epi8(accum, _mm256_setr_epi8(0, 2, 4, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 4, 6, 8, -1, -1, -1, -1, -1, -1));
h3 = _mm_or_si128(_mm256_extracti128_si256(shuf, 1), _mm256_castsi256_si128(shuf));
}
if (last_row_and_col) {
switch (cols_minus_j) {
case 15:
out[14] = static_cast<uint8_t>(_mm_extract_epi8(h3, 14));
case 14:
out[13] = static_cast<uint8_t>(_mm_extract_epi8(h3, 13));
case 13:
out[12] = static_cast<uint8_t>(_mm_extract_epi8(h3, 12));
case 12:
out[11] = static_cast<uint8_t>(_mm_extract_epi8(h3, 11));
case 11:
out[10] = static_cast<uint8_t>(_mm_extract_epi8(h3, 10));
case 10:
out[9] = static_cast<uint8_t>(_mm_extract_epi8(h3, 9));
case 9:
out[8] = static_cast<uint8_t>(_mm_extract_epi8(h3, 8));
case 8:
out[7] = static_cast<uint8_t>(_mm_extract_epi8(h3, 7));
case 7:
out[6] = static_cast<uint8_t>(_mm_extract_epi8(h3, 6));
case 6:
out[5] = static_cast<uint8_t>(_mm_extract_epi8(h3, 5));
case 5:
out[4] = static_cast<uint8_t>(_mm_extract_epi8(h3, 4));
case 4:
out[3] = static_cast<uint8_t>(_mm_extract_epi8(h3, 3));
case 3:
out[2] = static_cast<uint8_t>(_mm_extract_epi8(h3, 2));
case 2:
out[1] = static_cast<uint8_t>(_mm_extract_epi8(h3, 1));
case 1:
out[0] = static_cast<uint8_t>(_mm_extract_epi8(h3, 0));
}
}
else {
_mm_storeu_si128(reinterpret_cast<__m128i*>(out), h3);
}
}
template<bool last_row, bool weight>
void processRow(const uint8_t* __restrict pt, const int32_t cols, uint8_t* const __restrict out) {
int j = 0;
for (; j < cols - 10; j += 10, pt += 30) {
process<false, weight>(pt, cols - j, out + j);
}
process<last_row, weight>(pt, cols - j, out + j);
}
template<bool weight>
void __forceinline _RGB2Y(const uint8_t* __restrict const data, const int32_t cols, const int32_t start_row, const int32_t rows, const int32_t stride, uint8_t* const __restrict out) {
int i = start_row;
for (; i < start_row + rows - 1; ++i) {
processRow<false, weight>(data + 3 * i * stride, cols, out + i * cols);
}
processRow<true, weight>(data + 3 * i * stride, cols, out + i * cols);
}
template<bool multithread, bool weight>
void RGB2Y(const uint8_t* const __restrict image, const int width, const int height, const int stride, uint8_t* const __restrict out) {
if (multithread) {
const int32_t hw_concur = std::min(height >> 4, static_cast<int32_t>(std::thread::hardware_concurrency()));
if (hw_concur > 1) {
std::vector<std::future<void>> fut(hw_concur);
const int thread_stride = (height - 1) / hw_concur + 1;
int i = 0, start = 0;
for (; i < std::min(height - 1, hw_concur - 1); ++i, start += thread_stride) {
fut[i] = std::async(std::launch::async, _RGB2Y<weight>, image, width, start, thread_stride, stride, out);
}
fut[i] = std::async(std::launch::async, _RGB2Y<weight>, image, width, start, height - start, stride, out);
for (int j = 0; j <= i; ++j) fut[j].wait();
}
else {
_RGB2Y<weight>(image, width, 0, height, stride, out);
}
}
else {
_RGB2Y<weight>(image, width, 0, height, stride, out);
}
}
|
haominhe/Graduate
|
CS510 Operating System Foundations/P2/Main.c
|
code Main
-- OS Class: Project 2
--
-- <<NAME>>
--
-- This package contains the following:
-- SimpleThreadExample
-- MoreThreadExamples
-- ProducerConsumer
-- TestMutex
-- Dining Philospohers
-- References:
-- https://www.justsoftwaresolutions.co.uk/threading/locks-mutexes-semaphores.html
-- https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem
-- http://www.cs.fsu.edu/~baker/realtime/restricted/notes/prodcons.html
-- http://www.chegg.com/homework-help/questions-and-answers/implement-multi-threaded-producer-consumer-problem-pthreads-library-c-producer-consumer-co-q8539965
-- https://github.com/tgjamin
-- https://courses.engr.illinois.edu/cs241/sp2012/lectures/24-using_sem.pdf
-- http://www.geeksforgeeks.org/dining-philosophers-solution-using-monitors/
-- http://www.cs.fsu.edu/~baker/realtime/restricted/notes/philos.html
-- https://www.cs.indiana.edu/classes/p415-sjoh/hw/project/dining-philosophers/index.htm
-- https://github.com/JuShuck
-- https://github.com/ladinu
----------------------------- SynchTest ---------------------------------
function main ()
print ("Example Thread-based Programs...\n")
InitializeScheduler ()
----- Uncomment any one of the following to perform the desired test -----
-- SimpleThreadExample ()
-- MoreThreadExamples ()
-- TestMutex ()
-- ProducerConsumer ()
DiningPhilosophers ()
ThreadFinish ()
endFunction
----------------------------- SimpleThreadExample ---------------------------------
var aThread: Thread -- Don't put Thread objects on the stack, since the
-- routine that contains them may return!
function SimpleThreadExample ()
-- This code illustrates the basics of thread usage.
--
-- This code uses 2 threads. Each thread loops a few times.
-- Each loop iteration prints a message and executes a "Yield".
-- This code illustrates the following operations:
-- Thread creation
-- Fork
-- Yield
-- Thread termination
-- This code creates only one new thread; the currrent ("main") thread, which
-- already exists, is the other thread. Both the main thread and the newly
-- created thread will call function "SimpleThreadFunction" to perform the looping.
--
-- Notice that timer interrupts will also cause "Yields" to be inserted at
-- unpredictable places. Thus, the threads will not simply alternate.
--
-- Things to experiment with:
-- In TimerInterruptHandler (in Thread.c), uncomment "print ('_')".
-- In TimerInterruptHandler (in Thread.c), comment out the call to
-- Yield, which will suspend timeslicing.
-- Edit .blitzrc (see "sim" command) and change TIME_SLICE value.
-- In this function, comment out the call to "Yield".
--
print ("Simple Thread Example...\n")
aThread = new Thread
aThread.Init ("Second-Thread") -- Initialize, giving thread a name
aThread.Fork (SimpleThreadFunction, 4) -- Pass "4" as argument to the thread
SimpleThreadFunction (7) -- The main thread will loop 7 times
endFunction
function SimpleThreadFunction (cnt: int)
-- This function will loop "cnt" times. Each iteration will print a
-- message and execute a "Yield", which will give the other thread a
-- chance to run.
var i: int
for i = 1 to cnt
print (currentThread.name)
nl ()
currentThread.Yield ()
endFor
ThreadFinish ()
endFunction
----------------------------- MoreThreadExamples ---------------------------------
var th1, th2, th3, th4, th5, th6: Thread
function MoreThreadExamples ()
var j: int
oldStatus: int
print ("Thread Example...\n")
-- Create some thread objects (not on the heap).
th1 = new Thread
th2 = new Thread
th3 = new Thread
th4 = new Thread
th5 = new Thread
th6 = new Thread
-- Initialize them.
th1.Init ("thread-a")
th2.Init ("thread-b")
th3.Init ("thread-c")
th4.Init ("thread-d")
th5.Init ("thread-e")
th6.Init ("thread-f")
-- Start all threads running. Each thread will execute the "foo"
-- function, but each will be passed a different argument.
th1.Fork (foo, 1)
th2.Fork (foo, 2)
th3.Fork (foo, 3)
th4.Fork (foo, 4)
th5.Fork (foo, 5)
th6.Fork (foo, 6)
-- Print this thread's name. Note that we temporarily disable
-- interrupts so that all printing will happen together. Without
-- this, the other threads might print in the middle, causing a mess.
oldStatus = SetInterruptsTo (DISABLED)
print ("\nThe currently running thread is ")
print (currentThread.name)
print ("\n")
PrintReadyList ()
oldStatus = SetInterruptsTo (oldStatus)
for j = 1 to 10
currentThread.Yield ()
print ("\n..Main..\n")
endFor
-- Print the readyList at this point...
PrintReadyList ()
currentThread.Print()
/*
-- Put this thread to sleep...
oldStatus = SetInterruptsTo (DISABLED)
print ("About to Sleep main thread...\n")
currentThread.Sleep ()
FatalError ("BACK FROM SLEEP !?!?!")
-- Execution will never reach this point, since the current thread
-- was not placed on any list of waiting threads. Nothing in this
-- code could ever move this thread back to the ready list.
*/
ThreadFinish ()
endFunction
function foo (i: int)
var j: int
for j = 1 to 30
printInt (i)
if j == 20
-- Next is an example of aborting all threads and shutting down...
-- FatalError ("Whoops...(SAMPLE ERROR MESSAGE)")
-- Next is an example of just quietly shutting down...
-- RuntimeExit ()
-- Next is an example of what happens if execution errors occur...
-- i = j / 0 -- Generate an error
endIf
-- Call Yield so other threads can run. This is not necessary,
-- but it will cause more interleaving of the various threads,
-- making this program's output more interesting.
currentThread.Yield ()
endFor
endFunction
----------------------------- Test Mutex ---------------------------------
-- This code illustrates the ideas behind "critical sections" and "mutual
-- exclusion". This code creates several threads. Each thread accesses
-- some shared data (an integer) in a critical section. A single lock
-- is used to control access to the shared variable. Each thread locks
-- the mutex, computes a while, increments the integer, prints the new value,
-- updates the shared copy, and unlocks the mutex. Then it does some
-- non-critical computation and repeats.
var
myLock: Mutex = new Mutex -- Could also use "Mutex2" instead
sharedInt: int = 0
thArr: array [7] of Thread = new array of Thread {7 of new Thread }
function TestMutex ()
myLock.Init ()
print ("\n-- You should see 70 lines, each consecutively numbered. --\n\n")
thArr[0].Init ("LockTester-A")
thArr[0].Fork (LockTester, 100)
thArr[1].Init ("LockTester-B")
thArr[1].Fork (LockTester, 200)
thArr[2].Init ("LockTester-C")
thArr[2].Fork (LockTester, 1)
thArr[3].Init ("LockTester-D")
thArr[3].Fork (LockTester, 50)
thArr[4].Init ("LockTester-E")
thArr[4].Fork (LockTester, 300)
thArr[5].Init ("LockTester-F")
thArr[5].Fork (LockTester, 1)
thArr[6].Init ("LockTester-G")
thArr[6].Fork (LockTester, 1)
ThreadFinish ()
endFunction
function LockTester (waitTime: int)
-- This function will do the following actions, several times in a loop:
-- Lock the mutex
-- Get the current value of the "sharedInt" variable
-- Compute a new value by adding 1
-- Wait a while (determined by parameter "waitTime") to simulate
-- actions done within the critical section
-- Print the thread's name and the new value
-- Update the "sharedInt" variable
-- Unlock the mutex
-- Wait a while (determined by parameter "waitTime") to simulate
-- actions done outside of the critical section
var
i, j, k: int
for i = 1 to 10
-- Enter
myLock.Lock()
-- Critical Section
j = sharedInt + 1 -- read shared data
for k = 1 to waitTime -- do some computation
endFor --
printIntVar (currentThread.name, j) -- print new data value
sharedInt = j -- update shared data
-- Leave
myLock.Unlock()
-- Perform non-critical work
for k = 1 to waitTime
endFor
endFor
endFunction
----------------------------- ProducerConsumer ---------------------------------
-- This code implements the consumer-producer task. There are several
-- "producers", several "consumers", and a single shared buffer.
--
-- The producers are named "A", "B", "C", etc. Each producer is a thread which
-- will loop 5 times. For each iteration, the producer thread will add its
-- character to a shared buffer. For example, "Producer-B" will add 5 "B"s to
-- the shared buffer. Since the 5 producer threads will run concurrently, the
-- characters will be added in an unpredictable order. Regardless of the order,
-- however, there will be five "A"s, five "B"s, five "C"s, etc.
--
-- There are several consumers. Each consumer is a thread which executes an
-- inifinite loop. During each iteration of its loop, a consumer will remove
-- whatever character is next in the buffer and will print it.
--
-- The shared buffer is a FIFO queue of characters. The producers put characters
-- in one end and the consumers take characters out the other end. Think of a
-- section of steel pipe. The capacity of the buffer is limited to BUFFER_SIZE
-- characters.
--
-- This code illustrates the mechanisms required to synchronize the producers,
-- consumers, and the shared buffer. Consumers must wait if the buffer is empty.
-- Producers must wait if the buffer is full. Furthermore, the buffer is a shared
-- data structure. (The buffer is implemented as an array with pointers to the
-- next position to add or remove characters.) No two threads are allowed to
-- access these pointers simultaneously, or else errors may result.
--
-- To document what is happening, each producer will print a line when it adds
-- a character to the buffer. The line printed will include the buffer contents
-- along with the name of the poducer. Also, each time a consumer removes a
-- character from the buffer, it will print a line, showing the buffer contents
-- after the removal, along with the name of the consumer thread. Each line of
-- output is formated so that you can see the buffer growing and shrinking. By
-- reading the output vertically, you can also see what each thread does.
--
const
BUFFER_SIZE = 5 -- maximun of five characters in the buffer
var
buffer: array [BUFFER_SIZE] of char = new array of char {BUFFER_SIZE of '?'}
bufferSize: int = 0
bufferNextIn: int = 0
bufferNextOut: int = 0
-- 5 producer processes and 3 consumer processes
thArray: array [8] of Thread = new array of Thread { 8 of new Thread }
-- using the classes Mutex and Semaphore
fullbuffs: Semaphore = new Semaphore -- semaphore for wait and signal
emptybuffs: Semaphore = new Semaphore
mulock1: Mutex = new Mutex -- lock for insert and remove item
mulock2: Mutex = new Mutex
mulock3: Mutex = new Mutex
function ProducerConsumer ()
-- initialize lock and semaphores
mulock1.Init() -- for mutual exclusion
mulock2.Init()
mulock3.Init()
emptybuffs.Init(BUFFER_SIZE) -- number empty buffer entries
fullbuffs.Init(0) -- number full buffer entries
-- producer and consumer threads
print (" ")
thArray[0].Init ("Consumer-1 | ")
thArray[0].Fork (Consumer, 1)
thArray[1].Init ("Consumer-2 | ")
thArray[1].Fork (Consumer, 2)
thArray[2].Init ("Consumer-3 | ")
thArray[2].Fork (Consumer, 3)
thArray[3].Init ("Producer-A ")
thArray[3].Fork (Producer, 1)
thArray[4].Init ("Producer-B ")
thArray[4].Fork (Producer, 2)
thArray[5].Init ("Producer-C ")
thArray[5].Fork (Producer, 3)
thArray[6].Init ("Producer-D ")
thArray[6].Fork (Producer, 4)
thArray[7].Init ("Producer-E ")
thArray[7].Fork (Producer, 5)
ThreadFinish ()
endFunction
function Producer (myId: int)
var
i: int
c: char = intToChar ('A' + myId - 1)
for i = 1 to 5
-- Perform synchroniztion...
-- semaphore first, then lock, so do not go sleep with lock in hand
emptybuffs.Down() -- if buffer is full, wait in the waiting list
mulock1.Lock() -- lock the critical section
-- Add c to the buffer
buffer [bufferNextIn] = c
bufferNextIn = (bufferNextIn + 1) % BUFFER_SIZE
bufferSize = bufferSize + 1
-- Print a line showing the state
PrintBuffer (c)
-- Perform synchronization...
-- mulock.Unlock() -- unlock the critical section
fullbuffs.Up() -- wake up/signal the (sleeping) consumer thread
mulock1.Unlock() -- unlock the critical section
endFor
endFunction
function Consumer (myId: int)
var
c: char
while true
-- Perform synchroniztion...
fullbuffs.Down() -- if buffer is empty, sleep, wait in the waiting list
mulock2.Lock() -- lock the critical section
-- Remove next character from the buffer
c = buffer [bufferNextOut]
bufferNextOut = (bufferNextOut + 1) % BUFFER_SIZE
bufferSize = bufferSize - 1
-- Print a line showing the state
PrintBuffer (c)
-- Perform synchronization...
-- mulock.Unlock() -- unlock the critical section
emptybuffs.Up() -- wake up/signal the (sleeping) producer thread
mulock2.Unlock() -- unlock the critical section
endWhile
endFunction
function PrintBuffer (c: char)
--
-- This method prints the buffer and what we are doing to it. Each
-- line should have
-- <buffer> <threadname> <character involved>
-- We want to print the buffer as it was *before* the operation;
-- however, this method is called *after* the buffer has been modified.
-- To achieve the right order, we print the operation first, skip to
-- the next line, and then print the buffer. Assuming we start by
-- printing an empty buffer first, and we are willing to end the output
-- in the middle of a line, this prints things in the desired order.
--
var
i, j: int
mulock3.Lock()
-- Print the thread name, which tells what we are doing.
print (" ")
print (currentThread.name) -- Will include right number of spaces after name
printChar (c)
nl ()
-- Print the contents of the buffer.
j = bufferNextOut
for i = 1 to bufferSize
printChar (buffer[j])
j = (j + 1) % BUFFER_SIZE
endFor
-- Pad out with blanks to make things line up.
for i = 1 to BUFFER_SIZE-bufferSize
printChar (' ')
endFor
mulock3.Unlock()
endFunction
----------------------------- Dining Philosophers ---------------------------------
-- This code is an implementation of the Dining Philosophers problem. Each
-- philosopher is simulated with a thread. Each philosopher thinks for a while
-- and then wants to eat. Before eating, he must pick up both his forks.
-- After eating, he puts down his forks. Each fork is shared between
-- two philosophers and there are 5 philosophers and 5 forks arranged in a
-- circle.
--
-- Since the forks are shared, access to them is controlled by a monitor
-- called "ForkMonitor". The monitor is an object with two "entry" methods:
-- PickupForks (phil)
-- PutDownForks (phil)
-- The philsophers are numbered 0 to 4 and each of these methods is passed an integer
-- indicating which philospher wants to pickup (or put down) the forks.
-- The call to "PickUpForks" will wait until both of his forks are
-- available. The call to "PutDownForks" will never wait and may also
-- wake up threads (i.e., philosophers) who are waiting.
--
-- Each philospher is in exactly one state: HUNGRY, EATING, or THINKING. Each time
-- a philosopher's state changes, a line of output is printed. The output is organized
-- so that each philosopher has column of output with the following code letters:
-- E -- eating
-- . -- thinking
-- blank -- hungry (i.e., waiting for forks)
-- By reading down a column, you can see the history of a philosopher.
--
-- The forks are not modeled explicitly. A fork is only picked up
-- by a philospher if he can pick up both forks at the same time and begin
-- eating. To know whether a fork is available, it is sufficient to simply
-- look at the status's of the two adjacent philosophers. (Another way to state
-- the problem is to forget about the forks altogether and stipulate that a
-- philosopher may only eat when his two neighbors are not eating.)
enum HUNGRY, EATING, THINKING
var
mon: ForkMonitor
-- 5 philosphers/threads
philospher: array [5] of Thread = new array of Thread {5 of new Thread }
function DiningPhilosophers ()
print ("Plato\n")
print (" Sartre\n")
print (" Kant\n")
print (" Nietzsche\n")
print (" Aristotle\n")
mon = new ForkMonitor
mon.Init ()
mon.PrintAllStatus ()
philospher[0].Init ("Plato")
philospher[0].Fork (PhilosphizeAndEat, 0)
philospher[1].Init ("Sartre")
philospher[1].Fork (PhilosphizeAndEat, 1)
philospher[2].Init ("Kant")
philospher[2].Fork (PhilosphizeAndEat, 2)
philospher[3].Init ("Nietzsche")
philospher[3].Fork (PhilosphizeAndEat, 3)
philospher[4].Init ("Aristotle")
philospher[4].Fork (PhilosphizeAndEat, 4)
endFunction
function PhilosphizeAndEat (p: int)
-- The parameter "p" identifies which philosopher this is.
-- In a loop, he will think, acquire his forks, eat, and
-- put down his forks.
var
i: int
for i = 1 to 7
-- Now he is thinking
mon. PickupForks (p)
-- Now he is eating
mon. PutDownForks (p)
endFor
endFunction
class ForkMonitor
superclass Object
fields
-- need a mutex to protect the monitor itself
pmulock: Mutex
-- use the Condition class
pcondition: array [5] of Condition
status: array [5] of int -- For each philosopher: HUNGRY, EATING, or THINKING
methods
Init ()
PickupForks (p: int)
PutDownForks (p: int)
PrintAllStatus ()
test(p: int) -- test if I am hungry and my neighbors are not eating, so that I can eat
endClass
behavior ForkMonitor
method Init ()
var i: int
-- Initialize so that all philosophers are THINKING.
status = new array of int {5 of THINKING}
-- initialize lock
pmulock = new Mutex
pmulock.Init()
-- initialize conditions
pcondition = new array of Condition {5 of new Condition}
for i = 0 to 4
pcondition[i].Init()
endFor
endMethod
method PickupForks (p: int)
-- This method is called when philosopher 'p' is wants to eat.
-- first thing is to lock the monitor mutex
-- This will ensure that only one thread at a time is executing within the monitor
pmulock.Lock()
-- current philosopher is hungry, wants to eat
status[p] = HUNGRY
-- whenever the status changes of any philosopher
-- call PrintAllStatus. This method will print a line of output
self.PrintAllStatus()
-- check if I am able to eat or not, can eat if my neighbors are not eating
-- only call test with mutex set
self.test(p)
-- if my neighbor(s) is eating, I shall wait until I get an eating signal
-- we need to use a while loop here, because in the Condition, it implements "Mesa-style" semantics
-- in the time between a Signal() operation and the awakening
-- and execution of the corrsponding waiting thread, other threads may
-- have snuck in and run. The waiting thread should always re-check the
-- data to ensure that the condition which was signalled is still true
while(status[p] != EATING)
pcondition[p].Wait(&pmulock)
endWhile
-- before each of these methods returns, it must unlock the monitor
-- so that other threads can enter the monitor code
pmulock.Unlock()
endMethod
method test(p: int)
-- my left and right neighbors are not eating, I eat
if(status[p] == HUNGRY &&
status[(p+1)%5] != EATING &&
status[(p-1)%5] != EATING)
status[p] = EATING
-- print status changes
self.PrintAllStatus()
-- wake myself up / signal myself that I can eat, caught in PickUpForks Wait condition
pcondition[p].Signal(&pmulock)
endIf
endMethod
method PutDownForks (p: int)
-- This method is called when the philosopher 'p' is done eating.
-- lock the mutex before entering critical section
pmulock.Lock()
-- set myself back to thinking, and wake up my neighbors to eat
status[p] = THINKING
self.PrintAllStatus()
self.test((p+1)%5) -- test my left neighbor
self.test((p-1)%5) -- test my right neighbor
-- unlock mutex
pmulock.Unlock()
endMethod
method PrintAllStatus ()
-- Print a single line showing the status of all philosophers.
-- '.' means thinking
-- ' ' means hungry
-- 'E' means eating
-- Note that this method is internal to the monitor. Thus, when
-- it is called, the monitor lock will already have been acquired
-- by the thread. Therefore, this method can never be re-entered,
-- since only one thread at a time may execute within the monitor.
-- Consequently, printing is safe. This method calls the "print"
-- routine several times to print a single line, but these will all
-- happen without interuption.
var
p: int
for p = 0 to 4
switch status [p]
case HUNGRY:
print (" ")
break
case EATING:
print ("E ")
break
case THINKING:
print (". ")
break
endSwitch
endFor
nl ()
endMethod
endBehavior
endCode
|
haominhe/Graduate
|
CS510 Operating System Foundations/P3/Main.h
|
<reponame>haominhe/Graduate
header Main
uses System, Thread, Synch
functions
main ()
endHeader
|
haominhe/Graduate
|
CS510 Operating System Foundations/P2/Synch.h
|
<filename>CS510 Operating System Foundations/P2/Synch.h<gh_stars>0
header Synch
-- OS Class: Project 2
--
-- <<NAME>>
uses Thread
class Semaphore
superclass Object
fields
count: int
waitingThreads: List [Thread]
methods
Init (initialCount: int)
Down ()
Up ()
endClass
class Mutex
superclass Object
-- declare what attributes are in the init function
fields
waitingThreads : List [Thread]
muheldby : ptr to Thread
methods
Init ()
Lock ()
Unlock ()
IsHeldByCurrentThread () returns bool
endClass
class Condition
superclass Object
fields
waitingThreads: List [Thread]
methods
Init ()
Wait (mutex: ptr to Mutex)
Signal (mutex: ptr to Mutex)
Broadcast (mutex: ptr to Mutex)
endClass
endHeader
|
haominhe/Graduate
|
CS510 Operating System Foundations/P1/HelloWorld.h
|
<reponame>haominhe/Graduate
header Hello
uses System
functions
main ()
endHeader
|
haominhe/Graduate
|
CS510 Operating System Foundations/P4/Kernel.c
|
code Kernel
-- <NAME>
-- References:
-- http://web.cecs.pdx.edu/~harry/Blitz/InstructorInfo/IdeasOnHoareTask.pdf
-- http://www.cs.utexas.edu/users/lorenzo/corsi/cs372h/07S/notes/Lecture12.pdf
-- https://cseweb.ucsd.edu/classes/sp16/cse120-a/applications/ln/lecture9.html
-- http://pages.cs.wisc.edu/~remzi/OSTEP/threads-monitors.pdf
-- https://github.com/tgjamin/
-- https://github.com/ladinu/
-- https://github.com/obriematt/
-- https://github.com/JuShuck/
----------------------------- InitializeScheduler ---------------------------------
function InitializeScheduler ()
--
-- This routine assumes that we are in System mode. It sets up the
-- thread scheduler and turns the executing program into "main-thread".
-- After exit, we can execute "Yield", "Fork", etc. Upon return, the
-- main-thread will be executing with interrupts enabled.
--
Cleari ()
print ("Initializing Thread Scheduler...\n")
readyList = new List [Thread]
threadsToBeDestroyed = new List [Thread]
mainThread = new Thread
mainThread.Init ("main-thread")
mainThread.status = RUNNING
idleThread = new Thread
idleThread.Init ("idle-thread")
idleThread.Fork (IdleFunction, 0)
currentThread = & mainThread
FatalError = FatalError_ThreadVersion -- Use a routine which prints threadname
currentInterruptStatus = ENABLED
Seti ()
endFunction
----------------------------- IdleFunction ---------------------------------
function IdleFunction (arg: int)
--
-- This is the "idle thread", a kernel thread which ensures that the ready
-- list is never empty. The idle thread constantly yields to other threads
-- in an infinite loop. However, before yielding, it first checks to see if
-- there are other threads. If there are no other threads, the idle thread
-- will execute the "wait" instruction. The "wait" instruction will enable
-- interrupts and halt CPU execution until the next interrupt arrives.
--
var junk: int
while true
junk = SetInterruptsTo (DISABLED)
if readyList.IsEmpty ()
Wait ()
else
currentThread.Yield ()
endIf
endWhile
endFunction
----------------------------- Run ---------------------------------
function Run (nextThread: ptr to Thread)
--
-- Begin executing the thread "nextThread", which has already
-- been removed from the readyList. The current thread will
-- be suspended; we assume that its status has already been
-- changed to READY or BLOCKED. We assume that interrupts are
-- DISABLED when called.
--
-- This routine is called only from "Thread.Yield" and "Thread.Sleep".
--
-- It is allowable for nextThread to be currentThread.
--
var prevThread, th: ptr to Thread
prevThread = currentThread
prevThread.CheckOverflow ()
-- If the previous thread was using the USER registers, save them.
if prevThread.isUserThread
SaveUserRegs (&prevThread.userRegs[0])
endIf
currentThread = nextThread
nextThread.status = RUNNING
--print ("SWITCHING from ")
--print (prevThread.name)
--print (" to ")
--print (nextThread.name)
--print ("\n")
Switch (prevThread, nextThread)
--print ("After SWITCH, back in thread ")
--print (currentThread.name)
--print ("\n")
while ! threadsToBeDestroyed.IsEmpty ()
th = threadsToBeDestroyed.Remove()
threadManager.FreeThread (th)
endWhile
-- If the new thread uses the USER registers, restore them.
if currentThread.isUserThread
RestoreUserRegs (¤tThread.userRegs[0])
currentThread.myProcess.addrSpace.SetToThisPageTable ()
endIf
endFunction
----------------------------- PrintReadyList ---------------------------------
function PrintReadyList ()
--
-- This routine prints the readyList. It disables interrupts during the
-- printing to guarantee that the readyList won't change while it is
-- being printed, which could cause disaster in this routine!
--
var oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the ready list:\n")
readyList.ApplyToEach (ThreadPrintShort)
oldStatus = SetInterruptsTo (oldStatus)
endFunction
----------------------------- ThreadStartMain ---------------------------------
function ThreadStartMain ()
--
-- This function is called from the assembly language routine "ThreadStart"".
-- It is the first KPL code each thread will execute, and it will
-- invoke the thread's "main" function, with interrupts enabled. If the "main"
-- function ever returns, this function will terminate this thread. This
-- function will never return.
--
var
junk: int
mainFun: ptr to function (int)
-- print ("ThreadStartMain...\n")
junk = SetInterruptsTo (ENABLED)
mainFun = currentThread.initialFunction
mainFun (currentThread.initialArgument)
ThreadFinish ()
FatalError ("ThreadFinish should never return")
endFunction
----------------------------- ThreadFinish ---------------------------------
function ThreadFinish ()
--
-- As the last thing to do in this thread, we want to clean up
-- and reclaim the Thread object. This method is called as the
-- last thing the thread does; this is the normal way for a thread
-- to die. However, since the thread is still running in this,
-- we can't actually do the clean up. So we just make a note
-- that it is pending. After the next thread starts (in method "Run")
-- we'll finish the job.
--
var junk: int
junk = SetInterruptsTo (DISABLED)
-- print ("Finishing ")
-- print (currentThread.name)
-- print ("\n")
threadsToBeDestroyed.AddToEnd (currentThread)
currentThread.Sleep ()
-- Execution will never reach the next instruction
FatalError ("This thread will never run again")
endFunction
----------------------------- FatalError_ThreadVersion -----------------------
function FatalError_ThreadVersion (errorMessage: ptr to array of char)
--
-- This function will print out the name of the current thread and
-- the given error message. Then it will call "RuntimeExit" to
-- shutdown the system.
--
var
junk: int
junk = SetInterruptsTo (DISABLED)
print ("\nFATAL ERROR")
if currentThread -- In case errors occur before thread initialization
print (" in ")
print (currentThread.name)
endIf
print (": \"")
print (errorMessage)
print ("\" -- TERMINATING!\n\n")
print ("(To find out where execution was when the problem arose, type 'st' at the emulator prompt.)\n")
RuntimeExit ()
endFunction
----------------------------- SetInterruptsTo ---------------------------------
function SetInterruptsTo (newStatus: int) returns int
--
-- This routine is passed a status (DISABLED or ENABLED). It
-- returns the previous interrupt status and sets the interrupt
-- status to "newStatus".
--
-- Since this routine reads and modifies a shared variable
-- (currentInterruptStatus), there is a danger of this routine
-- being re-entered. Therefore, it momentarily will disable
-- interrupts, to ensure a valid update to this variable.
--
var
oldStat: int
Cleari ()
oldStat = currentInterruptStatus
if newStatus == ENABLED
currentInterruptStatus = ENABLED
Seti ()
else
currentInterruptStatus = DISABLED
Cleari ()
endIf
return oldStat
endFunction
----------------------------- Semaphore ---------------------------------
behavior Semaphore
-- This class provides the following methods:
-- Up() ...also known as "V" or "Signal"...
-- Increment the semaphore count. Wake up a thread if
-- there are any waiting. This operation always executes
-- quickly and will not suspend the thread.
-- Down() ...also known as "P" or "Wait"...
-- Decrement the semaphore count. If the count would go
-- negative, wait for some other thread to do an Up()
-- first. Conceptually, the count will never go negative.
-- Init(initialCount)
-- Each semaphore must be initialized. Normally, you should
-- invoke this method, providing an 'initialCount' of zero.
-- If the semaphore is initialized with 0, then a Down()
-- operation before any Up() will wait for the first
-- Up(). If initialized with i, then it is as if i Up()
-- operations have been performed already.
--
-- NOTE: The user should never look at a semaphore's count since the value
-- retrieved may be out-of-date, due to other threads performing Up() or
-- Down() operations since the retrieval of the count.'
---------- Semaphore . Init ----------
method Init (initialCount: int)
if initialCount < 0
FatalError ("Semaphore created with initialCount < 0")
endIf
count = initialCount
waitingThreads = new List [Thread]
endMethod
---------- Semaphore . Up ----------
method Up ()
var
oldIntStat: int
t: ptr to Thread
oldIntStat = SetInterruptsTo (DISABLED)
if count == 0x7fffffff
FatalError ("Semaphore count overflowed during 'Up' operation")
endIf
count = count + 1
if count <= 0
t = waitingThreads.Remove ()
t.status = READY
readyList.AddToEnd (t)
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
---------- Semaphore . Down ----------
method Down ()
var
oldIntStat: int
oldIntStat = SetInterruptsTo (DISABLED)
if count == 0x80000000
FatalError ("Semaphore count underflowed during 'Down' operation")
endIf
count = count - 1
if count < 0
waitingThreads.AddToEnd (currentThread)
currentThread.Sleep ()
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
endBehavior
----------------------------- Mutex ---------------------------------
behavior Mutex
-- This class provides the following methods:
-- Lock()
-- Acquire the mutex if free, otherwise wait until the mutex is
-- free and then get it.
-- Unlock()
-- Release the mutex. If other threads are waiting, then
-- wake up the oldest one and give it the lock.
-- Init()
-- Each mutex must be initialized.
-- IsHeldByCurrentThread()
-- Return TRUE iff the current (invoking) thread holds a lock
-- on the mutex.
----------- Mutex . Init -----------
method Init ()
waitingThreads = new List [Thread]
endMethod
----------- Mutex . Lock -----------
method Lock ()
var
oldIntStat: int
if heldBy == currentThread
FatalError ("Attempt to lock a mutex by a thread already holding it")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
if !heldBy
heldBy = currentThread
else
waitingThreads.AddToEnd (currentThread)
currentThread.Sleep ()
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
----------- Mutex . Unlock -----------
method Unlock ()
var
oldIntStat: int
t: ptr to Thread
if heldBy != currentThread
FatalError ("Attempt to unlock a mutex by a thread not holding it")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
t = waitingThreads.Remove ()
if t
t.status = READY
readyList.AddToEnd (t)
heldBy = t
else
heldBy = null
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
----------- Mutex . IsHeldByCurrentThread -----------
method IsHeldByCurrentThread () returns bool
return heldBy == currentThread
endMethod
endBehavior
----------------------------- Condition ---------------------------------
behavior Condition
-- This class is used to implement monitors. Each monitor will have a
-- mutex lock and one or more condition variables. The lock ensures that
-- only one process at a time may execute code in the monitor. Within the
-- monitor code, a thread can execute Wait() and Signal() operations
-- on the condition variables to make sure certain condions are met.
--
-- The condition variables here implement "Mesa-style" semantics, which
-- means that in the time between a Signal() operation and the awakening
-- and execution of the corrsponding waiting thread, other threads may
-- have snuck in and run. The waiting thread should always re-check the
-- data to ensure that the condition which was signalled is still true.
--
-- This class provides the following methods:
-- Wait(mutex)
-- This method assumes the mutex has alreasy been locked.
-- It unlocks it, and goes to sleep waiting for a signal on
-- this condition. When the signal is received, this method
-- re-awakens, re-locks the mutex, and returns.
-- Signal(mutex)
-- If there are any threads waiting on this condition, this
-- method will wake up the oldest and schedule it to run.
-- However, since this thread holds the mutex and never unlocks
-- it, the newly awakened thread will be forced to wait before
-- it can re-acquire the mutex and resume execution.
-- Broadcast(mutex)
-- This method is like Signal() except that it wakes up all
-- threads waiting on this condition, not just the next one.
-- Init()
-- Each condition must be initialized.
---------- Condition . Init ----------
method Init ()
waitingThreads = new List [Thread]
endMethod
---------- Condition . Wait ----------
method Wait (mutex: ptr to Mutex)
var
oldIntStat: int
if ! mutex.IsHeldByCurrentThread ()
FatalError ("Attempt to wait on condition when mutex is not held")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
mutex.Unlock ()
waitingThreads.AddToEnd (currentThread)
currentThread.Sleep ()
-- no need to lock the mutex, no need to wait for the next thread to acquire it
-- because we hand the lock off directly to the next thread
mutex.Lock ()
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
---------- Condition . Signal ----------
-- The code we have given you for the Signal method in the Condition class uses MESA
-- semantics. Change the implementation so that it uses Hoare semantics.
method Signal (mutex: ptr to Mutex)
var
oldIntStat: int
t: ptr to Thread
if ! mutex.IsHeldByCurrentThread ()
FatalError ("Attempt to signal a condition when mutex is not held")
endIf
-- disable interrupts, so that other threads cannot intervene the handing off lock process
oldIntStat = SetInterruptsTo (DISABLED)
t = waitingThreads.Remove ()
--mutex.heldBy = t -- handoff the lock to next thread in list for Hoare semantics
if t
t.status = READY
readyList.AddToEnd (t)
endIf
--mutex.Lock() -- give the lock to the next waking up thread
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
---------- Condition . Broadcast ----------
method Broadcast (mutex: ptr to Mutex)
var
oldIntStat: int
t: ptr to Thread
if ! mutex.IsHeldByCurrentThread ()
FatalError ("Attempt to broadcast a condition when lock is not held")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
while true
t = waitingThreads.Remove ()
if t == null
break
endIf
t.status = READY
readyList.AddToEnd (t)
endWhile
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
endBehavior
----------------------------- Thread ---------------------------------
behavior Thread
---------- Thread . Init ----------
method Init (n: String)
--
-- Initialize this Thread object, but do not schedule it for
-- execution yet.
--
name = n
status = JUST_CREATED
-- The next line initializes the systemStack array, without filling it in.
*((& systemStack) asPtrTo int) = SYSTEM_STACK_SIZE
systemStack [0] = STACK_SENTINEL
systemStack [SYSTEM_STACK_SIZE-1] = STACK_SENTINEL
stackTop = & (systemStack[SYSTEM_STACK_SIZE-1])
regs = new array of int { 13 of 0 }
isUserThread = false
userRegs = new array of int { 15 of 0 }
endMethod
---------- Thread . Fork ----------
method Fork (fun: ptr to function (int), arg: int)
--
-- This method will schedule this thread for execution; in other words
-- it will make it ready to run by adding it to the "ready queue." This
-- method is passed a function and a single integer argument. When the
-- thread runs, the thread will execute this function on that argument
-- and then termiante. This method will return after scheduling this
-- thread.
--
var
oldIntStat, junk: int
oldIntStat = SetInterruptsTo (DISABLED)
-- print ("Forking thread...\n")
initialFunction = fun
initialArgument = arg
stackTop = stackTop - 4
*(stackTop asPtrTo int) = ThreadStartUp asInteger
status = READY
readyList.AddToEnd (self)
junk = SetInterruptsTo (oldIntStat)
endMethod
---------- Thread . Yield ----------
method Yield ()
--
-- This method should only be invoked on the current thread. The
-- current thread may yield the processor to other threads by
-- executing:
-- currentThread.Yield ()
-- This method may be invoked with or without interrupts enabled.
-- Upon return, the interrupts will be in the same state; however
-- since other threads are given a chance to run and they may allow
-- interrupts, interrupts handlers may have been invoked before
-- this method returns.
--
var
nextTh: ptr to Thread
oldIntStat, junk: int
-- ASSERT:
if self != currentThread
FatalError ("In Yield, self != currentThread")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
-- print ("Yielding ")
-- print (name)
-- print ("\n")
nextTh = readyList.Remove ()
if nextTh
-- print ("About to run ")
-- print (nextTh.name)
-- print ("\n")
if status == BLOCKED
FatalError ("Status of current thread should be READY or RUNNING")
endIf
status = READY
readyList.AddToEnd (self)
Run (nextTh)
endIf
junk = SetInterruptsTo (oldIntStat)
endMethod
---------- Thread . Sleep ----------
method Sleep ()
--
-- This method should only be invoked on the current thread. It
-- will set the status of the current thread to BLCOKED and will
-- will switch to executing another thread. It is assumed that
-- (1) Interrupts are disabled before calling this routine, and
-- (2) The current thread has been placed on some other wait
-- list (e.g., for a Semaphore) or else the thread will
-- never get scheduled again.
--
var nextTh: ptr to Thread
-- ASSERT:
if currentInterruptStatus != DISABLED
FatalError ("In Sleep, currentInterruptStatus != DISABLED")
endIf
-- ASSERT:
if self != currentThread
FatalError ("In Sleep, self != currentThread")
endIf
-- print ("Sleeping ")
-- print (name)
-- print ("\n")
status = BLOCKED
nextTh = readyList.Remove ()
if nextTh == null
FatalError ("Ready list should always contain the idle thread")
endIf
Run (nextTh)
endMethod
---------- Thread . CheckOverflow ----------
method CheckOverflow ()
--
-- This method checks to see if this thread has overflowed its
-- pre-alloted stack space. WARNING: the approach taken here is only
-- guaranteed to work "with high probability".
--
if systemStack[0] != STACK_SENTINEL
FatalError ("System stack overflow detected!")
elseIf systemStack[SYSTEM_STACK_SIZE-1] != STACK_SENTINEL
FatalError ("System stack underflow detected!")
endIf
endMethod
---------- Thread . Print ----------
method Print ()
--
-- Print this object.
--
var i: int
oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print (" Thread \"")
print (name)
print ("\" (addr of Thread object: ")
printHex (self asInteger)
print (")\n")
print (" machine state:\n")
for i = 0 to 12
print (" r")
printInt (i+2)
print (": ")
printHex (regs[i])
print (" ")
printInt (regs[i])
print ("\n")
endFor
printHexVar (" stackTop", stackTop asInteger)
printHexVar (" stack starting addr", (& systemStack[0]) asInteger)
switch status
case JUST_CREATED:
print (" status = JUST_CREATED\n")
break
case READY:
print (" status = READY\n")
break
case RUNNING:
print (" status = RUNNING\n")
break
case BLOCKED:
print (" status = BLOCKED\n")
break
case UNUSED:
print (" status = UNUSED\n")
break
default:
FatalError ("Bad status in Thread")
endSwitch
print (" is user thread: ")
printBool (isUserThread)
nl ()
print (" user registers:\n")
for i = 0 to 14
print (" r")
printInt (i+1)
print (": ")
printHex (userRegs[i])
print (" ")
printInt (userRegs[i])
print ("\n")
endFor
oldStatus = SetInterruptsTo (oldStatus)
endMethod
endBehavior
----------------------------- ThreadPrintShort ---------------------------------
function ThreadPrintShort (t: ptr to Thread)
--
-- This function prints a single line giving the name of thread "t",
-- its status, and the address of the Thread object itself (which may be
-- helpful in distinguishing Threads when the name is not helpful).
--
var
oldStatus: int = SetInterruptsTo (DISABLED)
if !t
print ("NULL\n")
return
endIf
print (" Thread \"")
print (t.name)
print ("\" status=")
switch t.status
case JUST_CREATED:
print ("JUST_CREATED")
break
case READY:
print ("READY")
break
case RUNNING:
print ("RUNNING")
break
case BLOCKED:
print ("BLOCKED")
break
case UNUSED:
print ("UNUSED")
break
default:
FatalError ("Bad status in Thread")
endSwitch
print (" (addr of Thread object: ")
printHex (t asInteger)
print (")")
nl ()
-- t.Print ()
oldStatus = SetInterruptsTo (oldStatus)
endFunction
----------------------------- ThreadManager ---------------------------------
behavior ThreadManager
---------- ThreadManager . Init ----------
method Init ()
--
-- This method is called once at kernel startup time to initialize
-- the one and only "ThreadManager" object.
-- Top level language, declare variables at the top of the function
var
counter: int
print ("Initializing Thread Manager...\n")
-- IMPLEMENTED
-- initialize the array of threads -> initialize each thread in the array ->
-- set its status to UNUSED
threadTable = new array of Thread {MAX_NUMBER_OF_PROCESSES of new Thread}
freeList = new List [Thread]
-- a counter to loop through threadTable and modify corrsponding elements
for counter=0 to MAX_NUMBER_OF_PROCESSES - 1
threadTable[counter].Init("threadManager thread")
threadTable[counter].status = UNUSED
-- initialize the freeList -> place all Threads in the threadTable array
-- on the freeList during initialization
-- pass the address of current thread to list, instead of passing the actual thread object
freeList.AddToEnd(&threadTable[counter])
endFor
-- initialize the monitor lock and condition variable
threadManagerLock = new Mutex
threadManagerLock.Init()
aThreadBecameFree = new Condition
aThreadBecameFree.Init()
endMethod
---------- ThreadManager . Print ----------
method Print ()
--
-- Print each thread. Since we look at the freeList, this
-- routine disables interrupts so the printout will be a
-- consistent snapshot of things.
--
var i, oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the thread table...\n")
for i = 0 to MAX_NUMBER_OF_PROCESSES-1
print (" ")
printInt (i)
print (":")
ThreadPrintShort (&threadTable[i])
endFor
print ("Here is the FREE list of Threads:\n ")
freeList.ApplyToEach (PrintObjectAddr)
nl ()
oldStatus = SetInterruptsTo (oldStatus)
endMethod
---------- ThreadManager . GetANewThread ----------
method GetANewThread () returns ptr to Thread
--
-- This method returns a new Thread; it will wait
-- until one is available.
-- if we have free thread slot in the freeList, we hand it to the caller who wants a thread
-- return a local variable pointer, initialize to null
var temp : ptr to Thread
temp = null
-- IMPLEMENTED
-- GetANewThread is an entry method -> must obtain the
-- monitor lock in the first statement and release it in the last statement
threadManagerLock.Lock()
-- If the freeList is empty, this method will need to wait on the condition
-- of a thread becoming available.
-- use while for MESA, use if for Hoare semantics
while freeList.IsEmpty()
aThreadBecameFree.Wait(&threadManagerLock)
endWhile
--if freeList.IsEmpty()
--aThreadBecameFree.Wait(&threadManagerLock)
--endIf
-- If there are avaiable threads, GetANewThread will remove and return a Thread
-- from the freeList.
temp = freeList.Remove() -- get the pointer to the current thread
-- change the Thread status to JUST_CREATED
temp.status = JUST_CREATED
threadManagerLock.Unlock()
return temp
endMethod
---------- ThreadManager . FreeThread ----------
method FreeThread (th: ptr to Thread)
--
-- This method is passed a ptr to a Thread; It moves it
-- to the FREE list.
-- Every thread that terminates will be added back to the freeList
-- IMPLEMENTED
-- FreeThread is an entry method -> must obtain the
-- monitor lock in the first statement and release it in the last statement
threadManagerLock.Lock()
-- The FreeThread method will add a Thread back to the freeList and
-- signal anyone waiting on the condition
-- change the Thread status to UNUSED
th.status = UNUSED
freeList.AddToEnd(th)
aThreadBecameFree.Signal(&threadManagerLock)
threadManagerLock.Unlock()
endMethod
endBehavior
-------------------------- ProcessControlBlock ------------------------------
behavior ProcessControlBlock
---------- ProcessControlBlock . Init ----------
--
-- This method is called once for every PCB at startup time.
--
method Init ()
pid = -1
status = FREE
addrSpace = new AddrSpace
addrSpace.Init ()
-- Uncomment this code later...
/*
fileDescriptor = new array of ptr to OpenFile
{ MAX_FILES_PER_PROCESS of null }
*/
endMethod
---------- ProcessControlBlock . Print ----------
method Print ()
--
-- Print this ProcessControlBlock using several lines.
--
-- var i: int
self.PrintShort ()
addrSpace.Print ()
print (" myThread = ")
ThreadPrintShort (myThread)
-- Uncomment this code later...
/*
print (" File Descriptors:\n")
for i = 0 to MAX_FILES_PER_PROCESS-1
if fileDescriptor[i]
fileDescriptor[i].Print ()
endIf
endFor
*/
nl ()
endMethod
---------- ProcessControlBlock . PrintShort ----------
method PrintShort ()
--
-- Print this ProcessControlBlock on one line.
--
print (" ProcessControlBlock (addr=")
printHex (self asInteger)
print (") pid=")
printInt (pid)
print (", status=")
if status == ACTIVE
print ("ACTIVE")
elseIf status == ZOMBIE
print ("ZOMBIE")
elseIf status == FREE
print ("FREE")
else
FatalError ("Bad status in ProcessControlBlock")
endIf
print (", parentsPid=")
printInt (parentsPid)
print (", exitStatus=")
printInt (exitStatus)
nl ()
endMethod
endBehavior
----------------------------- ProcessManager ---------------------------------
behavior ProcessManager
---------- ProcessManager . Init ----------
method Init ()
--
-- This method is called once at kernel startup time to initialize
-- the one and only "processManager" object.
-- these are resources which must be allocated. This is the purpose of the monitor
-- class called ProcessManager
-- IMPLEMENTED
var counter : int
processTable = new array of ProcessControlBlock {MAX_NUMBER_OF_PROCESSES of new ProcessControlBlock}
-- freeList is a list of all ProcessControlBlocks that are FREE
freeList = new List [ProcessControlBlock]
-- The status of a ProcessControlBlock should be FREE if and only
-- if it is on the freeList.
-- initialize all the ProcessControlBlocks in processTable array
for counter=0 to MAX_NUMBER_OF_PROCESSES - 1
processTable[counter].Init()
-- we should set status to FREE since we added it to the freeList
processTable[counter].status = FREE
-- pass the address of current ProcessControlBlock to list
freeList.AddToEnd(& processTable[counter])
endFor
-- we will ignore the ZOMBIE state. Every process will be either ACTIVE or
-- FREE. ignore aProcessDied, but should be initialized nonetheless.
processManagerLock = new Mutex -- These synchronization objects
processManagerLock.Init()
aProcessBecameFree = new Condition -- apply to the "freeList"
aProcessBecameFree.Init()
-- aProcessDied is signaled when a process goes from ACTIVE to ZOMBIE
aProcessDied = new Condition
aProcessDied.Init()
-- Each process will have a unique process ID (the field named pid).
nextPid = 0
endMethod
---------- ProcessManager . Print ----------
method Print ()
--
-- Print all processes. Since we look at the freeList, this
-- routine disables interrupts so the printout will be a
-- consistent snapshot of things.
--
var i, oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the process table...\n")
for i = 0 to MAX_NUMBER_OF_PROCESSES-1
print (" ")
printInt (i)
print (":")
processTable[i].Print ()
endFor
print ("Here is the FREE list of ProcessControlBlocks:\n ")
freeList.ApplyToEach (PrintObjectAddr)
nl ()
oldStatus = SetInterruptsTo (oldStatus)
endMethod
---------- ProcessManager . PrintShort ----------
method PrintShort ()
--
-- Print all processes. Since we look at the freeList, this
-- routine disables interrupts so the printout will be a
-- consistent snapshot of things.
--
var i, oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the process table...\n")
for i = 0 to MAX_NUMBER_OF_PROCESSES-1
print (" ")
printInt (i)
processTable[i].PrintShort ()
endFor
print ("Here is the FREE list of ProcessControlBlocks:\n ")
freeList.ApplyToEach (PrintObjectAddr)
nl ()
oldStatus = SetInterruptsTo (oldStatus)
endMethod
---------- ProcessManager . GetANewProcess ----------
method GetANewProcess () returns ptr to ProcessControlBlock
--
-- This method returns a new ProcessControlBlock; it will wait
-- until one is available.
-- In our kernel, each user-level process will contain only one thread.
-- return a local variable pointer, initialize to null
var temp : ptr to ProcessControlBlock
temp = null
-- IMPLEMENTED
-- several threads may simultaneously request a new ProcessControlBlock by calling
-- GetANewProcess. The ProcessManager is a “monitor,” in order to protect the
-- freeList from concurrent access -> use Mutex
processManagerLock.Lock()
-- If the freeList is empty, wait on the condition of a ProcessControlBlock becoming availiable
-- use while for MESA, use if for Hoare semantics
while freeList.IsEmpty()
aProcessBecameFree.Wait(& processManagerLock)
endWhile
--if freeList.IsEmpty()
--aProcessBecameFree.Wait(& processManagerLock)
--endIf
-- If there are avaiable threads, remove and return a ProcessControlBlock from the freeList
temp = freeList.Remove() -- get the pointer to the current ProcessControlBlock
-- change the ProcessControlBlock to ACTIVE
temp.status = ACTIVE
-- Every time a ProcessControlBlock is allocated
-- this integer must be incremented and used to set the process’s pid
nextPid = nextPid + 1
-- assign a process ID to this ProcessControlBlock
temp.pid = nextPid
processManagerLock.Unlock()
return temp
endMethod
---------- ProcessManager . FreeProcess ----------
method FreeProcess (p: ptr to ProcessControlBlock)
--
-- This method is passed a ptr to a Process; It moves it
-- to the FREE list.
-- Both GetANewProcess and FreeProcess are monitor entry methods
-- IMPLEMENTED
processManagerLock.Lock()
-- When a ProcessControlBlock is added to the freeList, the condition aProcessBecameFree
-- can be Signaled to wake up any thread waiting for a ProcessControlBlock.
-- we should set status to FREE since we added it to the freeList
p.status = FREE
freeList.AddToEnd(p)
aProcessBecameFree.Signal(& processManagerLock)
processManagerLock.Unlock()
endMethod
endBehavior
----------------------------- PrintObjectAddr ---------------------------------
function PrintObjectAddr (p: ptr to Object)
--
-- Print the address of the given object.
--
printHex (p asInteger)
printChar (' ')
endFunction
----------------------------- ProcessFinish --------------------------
function ProcessFinish (exitStatus: int)
--
-- This routine is called when a process is to be terminated. It will
-- free the resources held by this process and will terminate the
-- current thread.
--
FatalError ("ProcessFinish is not implemented")
endFunction
----------------------------- FrameManager ---------------------------------
behavior FrameManager
---------- FrameManager . Init ----------
method Init ()
--
-- This method is called once at kernel startup time to initialize
-- the one and only "frameManager" object.
--
var i: int
print ("Initializing Frame Manager...\n")
framesInUse = new BitMap
framesInUse.Init (NUMBER_OF_PHYSICAL_PAGE_FRAMES)
numberFreeFrames = NUMBER_OF_PHYSICAL_PAGE_FRAMES
frameManagerLock = new Mutex
frameManagerLock.Init ()
newFramesAvailable = new Condition
newFramesAvailable.Init ()
-- Check that the area to be used for paging contains zeros.
-- The BLITZ emulator will initialize physical memory to zero, so
-- if by chance the size of the kernel has gotten so large that
-- it runs into the area reserved for pages, we will detect it.
-- Note: this test is not 100%, but is included nonetheless.
for i = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME
to PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME+300
by 4
if 0 != *(i asPtrTo int)
FatalError ("Kernel code size appears to have grown too large and is overflowing into the frame region")
endIf
endFor
endMethod
---------- FrameManager . Print ----------
method Print ()
--
-- Print which frames are allocated and how many are free.
--
frameManagerLock.Lock ()
print ("FRAME MANAGER:\n")
printIntVar (" numberFreeFrames", numberFreeFrames)
print (" Here are the frames in use: \n ")
framesInUse.Print ()
frameManagerLock.Unlock ()
endMethod
---------- FrameManager . GetAFrame ----------
method GetAFrame () returns int
--
-- Allocate a single frame and return its physical address. If no frames
-- are currently available, wait until the request can be completed.
--
var f, frameAddr: int
-- Acquire exclusive access to the frameManager data structure...
frameManagerLock.Lock ()
-- Wait until we have enough free frames to entirely satisfy the request...
while numberFreeFrames < 1
newFramesAvailable.Wait (&frameManagerLock)
endWhile
-- Find a free frame and allocate it...
f = framesInUse.FindZeroAndSet ()
numberFreeFrames = numberFreeFrames - 1
-- Unlock...
frameManagerLock.Unlock ()
-- Compute and return the physical address of the frame...
frameAddr = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME + (f * PAGE_SIZE)
-- printHexVar ("GetAFrame returning frameAddr", frameAddr)
return frameAddr
endMethod
---------- FrameManager . GetNewFrames ----------
method GetNewFrames (aPageTable: ptr to AddrSpace, numFramesNeeded: int)
-- 2^13 = 8192
-- Each frame is a resource. a thread will request some frames; the frameManager
-- will either be able to satisfy the request, or the requesting thread will have
-- to wait until the request can be satisfied.
-- IMPLEMENTED
var i , f , frameAddr : int
-- Acquire the frame manager lock.
frameManagerLock.Lock ()
-- GetANewFrame allocates one frame (waiting until at least one is available) and
-- returns the address of the frame.
-- Wait on newFramesAvailable until there are enough free frames to satisfy the request.
-- while for MESA, if for Hoare
while numberFreeFrames < numFramesNeeded
newFramesAvailable.Wait (&frameManagerLock)
endWhile
--if numberFreeFrames < numFramesNeeded
--newFramesAvailable.Wait (&frameManagerLock)
--endIf
-- Do a loop for each of the frames
for i = 0 to numFramesNeeded-1
-- determine which frame is free (find and set a bit in the framesInUse BitMap)
-- Find a free frame and allocate it...
f = framesInUse.FindZeroAndSet ()
-- figure out the address of the free frame
-- Compute the physical address of the frame...
frameAddr = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME + (f * PAGE_SIZE)
-- When the frames are gotten, the GetNewFrames method needs to make a note of which
-- frames have been allocated. It does this by storing the address of each frame it
-- allocates (the address of the first byte in each frame) into an AddrSpace object
-- An AddrSpace object is used to represent a virtual address space and to tell where
-- in physical memory the virtual pages are actually located.
-- aPageTable : ptr to AddrSpace
-- to store the address of the frame which has been allocated
aPageTable.SetFrameAddr (i, frameAddr)
-- Adjust the number of free frames
numberFreeFrames = numberFreeFrames - 1
endFor
-- Set aPageTable.numberOfPages to the number of frames allocated
aPageTable.numberOfPages = aPageTable.numberOfPages + i
-- Unlock the frame manager
frameManagerLock.Unlock ()
endMethod
---------- FrameManager . ReturnAllFrames ----------
method ReturnAllFrames (aPageTable: ptr to AddrSpace)
-- there is never a need to return frames one at a time
-- IMPLEMENTED
var i, frameAddr, bitNumber : int
-- Acquire the frame manager lock.
frameManagerLock.Lock ()
-- It can look at aPageTable.numberOfPages to see how many are being returned.
-- It can then go through the page table and see which frames it possessed. For each,
-- it can clear the bit.
for i = 0 to aPageTable.numberOfPages - 1
frameAddr = aPageTable.ExtractFrameAddr (i)
-- do the opposite calculation
-- frameAddr = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME + (f * PAGE_SIZE)
bitNumber = (frameAddr - PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME) / PAGE_SIZE
framesInUse.ClearBit(bitNumber)
numberFreeFrames = numberFreeFrames + 1
newFramesAvailable.Signal(&frameManagerLock)
endFor
-- adjust the number of free frames and “notify” any waiting threads that more frames
-- have become available.
-- The thread that gets awakened may not have enough free frames to complete, but other
-- waiting threads may be able to proceed.
-- newFramesAvailable.Broadcast(&frameManagerLock)
aPageTable.numberOfPages = aPageTable.numberOfPages - i
-- Unlock the frame manager
frameManagerLock.Unlock ()
endMethod
endBehavior
----------------------------- AddrSpace ---------------------------------
behavior AddrSpace
---------- AddrSpace . Init ----------
method Init ()
--
-- Initialize this object.
--
numberOfPages = 0
pageTable = new array of int { MAX_PAGES_PER_VIRT_SPACE of 0x00000003 }
endMethod
---------- AddrSpace . Print ----------
method Print ()
--
-- Print this object.
--
var i: int
print (" addr entry Logical Physical Undefined Bits Dirty Referenced Writeable Valid\n")
print (" ========== ========== ========== ========== ============== ===== ========== ========= =====\n")
for i = 0 to numberOfPages-1
print (" ")
printHex ((&pageTable[i]) asInteger)
print (": ")
printHex (pageTable[i])
print (" ")
printHex (i * PAGE_SIZE) -- Logical address
print (" ")
printHex (self.ExtractFrameAddr (i)) -- Physical address
print (" ")
if self.ExtractUndefinedBits (i) != 0
printHex (self.ExtractUndefinedBits (i))
else
print (" ")
endIf
print (" ")
if self.IsDirty (i)
print ("YES")
else
print (" ")
endIf
print (" ")
if self.IsReferenced (i)
print ("YES")
else
print (" ")
endIf
print (" ")
if self.IsWritable (i)
print ("YES")
else
print (" ")
endIf
print (" ")
if self.IsValid (i)
print ("YES")
else
print (" ")
endIf
nl ()
endFor
endMethod
---------- AddrSpace . ExtractFrameAddr ----------
method ExtractFrameAddr (entry: int) returns int
--
-- Return the physical address of the frame in the selected page
-- table entry.
--
return (pageTable[entry] & 0xffffe000)
endMethod
---------- AddrSpace . ExtractUndefinedBits ----------
method ExtractUndefinedBits (entry: int) returns int
--
-- Return the undefined bits in the selected page table entry.
--
return (pageTable[entry] & 0x00001ff0)
endMethod
---------- AddrSpace . SetFrameAddr ----------
method SetFrameAddr (entry: int, frameAddr: int)
--
-- Set the physical address of the frame in the selected page
-- table entry to the value of the argument "frameAddr".
--
pageTable[entry] = (pageTable[entry] & 0x00001fff) | frameAddr
endMethod
---------- AddrSpace . IsDirty ----------
method IsDirty (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "dirty".
--
return (pageTable[entry] & 0x00000008) != 0
endMethod
---------- AddrSpace . IsReferenced ----------
method IsReferenced (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "referenced".
--
return (pageTable[entry] & 0x00000004) != 0
endMethod
---------- AddrSpace . IsWritable ----------
method IsWritable (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "writable".
--
return (pageTable[entry] & 0x00000002) != 0
endMethod
---------- AddrSpace . IsValid ----------
method IsValid (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "valid".
--
return (pageTable[entry] & 0x00000001) != 0
endMethod
---------- AddrSpace . SetDirty ----------
method SetDirty (entry: int)
--
-- Set the selected page table entry's "dirty" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000008
endMethod
---------- AddrSpace . SetReferenced ----------
method SetReferenced (entry: int)
--
-- Set the selected page table entry's "referenced" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000004
endMethod
---------- AddrSpace . SetWritable ----------
method SetWritable (entry: int)
--
-- Set the selected page table entry's "writable" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000002
endMethod
---------- AddrSpace . SetValid ----------
method SetValid (entry: int)
--
-- Set the selected page table entry's "valid" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000001
endMethod
---------- AddrSpace . ClearDirty ----------
method ClearDirty (entry: int)
--
-- Clear the selected page table entry's "dirty" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000008
endMethod
---------- AddrSpace . ClearReferenced ----------
method ClearReferenced (entry: int)
--
-- Clear the selected page table entry's "referenced" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000004
endMethod
---------- AddrSpace . ClearWritable ----------
method ClearWritable (entry: int)
--
-- Clear the selected page table entry's "writable" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000002
endMethod
---------- AddrSpace . ClearValid ----------
method ClearValid (entry: int)
--
-- Clear the selected page table entry's "valid" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000001
endMethod
---------- AddrSpace . SetToThisPageTable ----------
method SetToThisPageTable ()
--
-- This method sets the page table registers in the CPU to
-- point to this page table. Later, when paging is enabled,
-- this will become the active virtual address space.
--
LoadPageTableRegs ((& pageTable[0]) asInteger, numberOfPages*4)
endMethod
---------- AddrSpace . CopyBytesFromVirtual ----------
method CopyBytesFromVirtual (kernelAddr, virtAddr, numBytes: int)
returns int
--
-- This method copies data from a user's virtual address space
-- to somewhere in the kernel space. We assume that the
-- pages of the virtual address space are resident in
-- physical page frames. This routine returns the number of bytes
-- that were copied; if there was any problem with the virtual
-- addressed data, it returns -1.
--
var copiedSoFar, virtPage, offset, fromAddr: int
-- print ("CopyBytesFromVirtual called...\n")
-- printHexVar (" kernelAddr", kernelAddr)
-- printHexVar (" virtAddr", virtAddr)
-- printIntVar (" numBytes", numBytes)
if numBytes == 0
return 0
elseIf numBytes < 0
return -1
endIf
virtPage = virtAddr / PAGE_SIZE
offset = virtAddr % PAGE_SIZE
-- printHexVar (" virtPage", virtPage)
-- printHexVar (" offset", offset)
while true
if virtPage >= numberOfPages
print (" Virtual page number is too large!!!\n")
return -1
endIf
if ! self.IsValid (virtPage)
print (" Virtual page is not marked VALID!!!\n")
return -1
endIf
fromAddr = self.ExtractFrameAddr (virtPage) + offset
-- printHexVar (" Copying bytes from physcial addr", fromAddr)
while offset < PAGE_SIZE
-- printHexVar (" Copying a byte to physcial addr", kernelAddr)
-- printChar (* (fromAddr asPtrTo char))
* (kernelAddr asPtrTo char) = * (fromAddr asPtrTo char)
offset = offset + 1
kernelAddr = kernelAddr + 1
fromAddr = fromAddr + 1
copiedSoFar = copiedSoFar + 1
if copiedSoFar == numBytes
return copiedSoFar
endIf
endWhile
virtPage = virtPage + 1
offset = 0
endWhile
endMethod
---------- AddrSpace . CopyBytesToVirtual ----------
method CopyBytesToVirtual (virtAddr, kernelAddr, numBytes: int)
returns int
--
-- This method copies data from the kernel's address space to
-- somewhere in the virtual address space. We assume that the
-- pages of the virtual address space are resident in physical
-- page frames. This routine returns the number of bytes
-- that were copied; if there was any problem with the virtual
-- addressed data, it returns -1.
--
var copiedSoFar, virtPage, offset, destAddr: int
if numBytes == 0
return 0
elseIf numBytes < 0
return -1
endIf
virtPage = virtAddr / PAGE_SIZE
offset = virtAddr % PAGE_SIZE
while true
if (virtPage >= numberOfPages) ||
(! self.IsValid (virtPage)) ||
(! self.IsWritable (virtPage))
return -1
endIf
destAddr = self.ExtractFrameAddr (virtPage) + offset
while offset < PAGE_SIZE
* (destAddr asPtrTo char) = * (kernelAddr asPtrTo char)
offset = offset + 1
kernelAddr = kernelAddr + 1
destAddr = destAddr + 1
copiedSoFar = copiedSoFar + 1
if copiedSoFar == numBytes
return copiedSoFar
endIf
endWhile
virtPage = virtPage + 1
offset = 0
endWhile
endMethod
---------- AddrSpace . GetStringFromVirtual ----------
method GetStringFromVirtual (kernelAddr: String, virtAddr, maxSize: int) returns int
--
-- This method is used to copy a String from virtual space into
-- a given physical address in the kernel. The "kernelAddr" should be
-- a pointer to an "array of char" in the kernel's code. This method
-- copies up to "maxSize" characters from approriate page frame to this
-- to the target array in the kernel.'
--
-- Note: This method resets the "arraySize" word in the target. It is
-- assumed that the target array has enough space; no checking is done.
-- The caller should supply a "maxSize" telling how many characters may
-- be safely copied.
--
-- If there are problems, then -1 is returned. Possible problems:
-- The source array has more than "maxSize" elements
-- The source page is invalid or out of range
-- If all okay, then the number of characters copied is returned.
--
var sourceSize: int
-- print ("GetStringFromVirtual called...\n")
-- printHexVar (" kernelAddr", kernelAddr asInteger)
-- printHexVar (" virtAddr", virtAddr)
-- printIntVar (" maxSize", maxSize)
-- Begin by fetching the source size
if self.CopyBytesFromVirtual ((&sourceSize) asInteger,
virtAddr,
4) < 4
return -1
endIf
-- printIntVar (" sourceSize", sourceSize)
-- Make sure the source size is okay
if sourceSize > maxSize
return -1
endIf
-- Change the size of the destination array
* (kernelAddr asPtrTo int) = sourceSize
-- Next, get the characters
return self.CopyBytesFromVirtual (kernelAddr asInteger + 4,
virtAddr + 4,
sourceSize)
endMethod
endBehavior
----------------------------- TimerInterruptHandler ---------------------------------
function TimerInterruptHandler ()
--
-- This routine is called when a timer interrupt occurs. Upon entry,
-- interrupts are DISABLED. Upon return, execution will return to
-- the interrupted process, which necessarily had interrupts ENABLED.
--
-- (If you wish to turn time-slicing off, simply disable the call
-- to "Yield" in the code below. Threads will then execute until they
-- call "Yield" explicitly, or until they call "Sleep".)
--
currentInterruptStatus = DISABLED
-- printChar ('_')
currentThread.Yield ()
currentInterruptStatus = ENABLED
endFunction
----------------------------- DiskInterruptHandler --------------------------
function DiskInterruptHandler ()
--
-- This routine is called when a disk interrupt occurs. It will
-- signal the "semToSignalOnCompletion" Semaphore and return to
-- the interrupted thread.
--
-- This is an interrupt handler. As such, interrupts will be DISABLED
-- for the duration of its execution.
--
-- Uncomment this code later...
FatalError ("DISK INTERRUPTS NOT EXPECTED IN PROJECT 4")
/*
currentInterruptStatus = DISABLED
-- print ("DiskInterruptHandler invoked!\n")
if diskDriver.semToSignalOnCompletion
diskDriver.semToSignalOnCompletion.Up()
endIf
*/
endFunction
----------------------------- SerialInterruptHandler --------------------------
function SerialInterruptHandler ()
--
-- This routine is called when a serial interrupt occurs. It will
-- signal the "semToSignalOnCompletion" Semaphore and return to
-- the interrupted thread.
--
-- This is an interrupt handler. As such, interrupts will be DISABLED
-- for the duration of its execution.
--
currentInterruptStatus = DISABLED
-- NOT IMPLEMENTED
endFunction
----------------------------- IllegalInstructionHandler --------------------------
function IllegalInstructionHandler ()
--
-- This routine is called when an IllegalInstruction exception occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An IllegalInstruction exception has occured while in user mode")
endFunction
----------------------------- ArithmeticExceptionHandler --------------------------
function ArithmeticExceptionHandler ()
--
-- This routine is called when an ArithmeticException occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An ArithmeticException exception has occured while in user mode")
endFunction
----------------------------- AddressExceptionHandler --------------------------
function AddressExceptionHandler ()
--
-- This routine is called when an AddressException occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An AddressException exception has occured while in user mode")
endFunction
----------------------------- PageInvalidExceptionHandler --------------------------
function PageInvalidExceptionHandler ()
--
-- This routine is called when a PageInvalidException occurs. Upon entry,
-- interrupts are DISABLED. For now, we simply print a message and abort
-- the thread.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("A PageInvalidException exception has occured while in user mode")
endFunction
----------------------------- PageReadonlyExceptionHandler --------------------------
function PageReadonlyExceptionHandler ()
--
-- This routine is called when a PageReadonlyException occurs. Upon entry,
-- interrupts are DISABLED. For now, we simply print a message and abort
-- the thread.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("A PageReadonlyException exception has occured while in user mode")
endFunction
----------------------------- PrivilegedInstructionHandler --------------------------
function PrivilegedInstructionHandler ()
--
-- This routine is called when a PrivilegedInstruction exception occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("A PrivilegedInstruction exception has occured while in user mode")
endFunction
----------------------------- AlignmentExceptionHandler --------------------------
function AlignmentExceptionHandler ()
--
-- This routine is called when an AlignmentException occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An AlignmentException exception has occured while in user mode")
endFunction
----------------------------- ErrorInUserProcess --------------------------
function ErrorInUserProcess (errorMessage: String)
--
-- This routine is called when an error has occurred in a user-level
-- process. It prints the error message and terminates the process.
--
print ("\n********** ")
print (errorMessage)
print (" **********\n\n")
-- Print some information about the offending process...
if currentThread.myProcess
currentThread.myProcess.Print ()
else
print (" ERROR: currentThread.myProcess is null\n\n")
endIf
currentThread.Print ()
-- Uncomment the following for even more information...
-- threadManager.Print ()
-- processManager.Print ()
ProcessFinish (-1)
endFunction
----------------------------- SyscallTrapHandler --------------------------
function SyscallTrapHandler (syscallCodeNum, arg1, arg2, arg3, arg4: int) returns int
--
-- This routine is called when a syscall trap occurs. Upon entry, interrupts
-- will be DISABLED, paging is disabled, and we will be running in System mode.
-- Upon return, execution will return to the user mode portion of this
-- thread, which will have had interrupts ENABLED.
--
currentInterruptStatus = DISABLED
/*****
print ("Within SyscallTrapHandler: syscallCodeNum=")
printInt (syscallCodeNum)
print (", arg1=")
printInt (arg1)
print (", arg2=")
printInt (arg2)
print (", arg3=")
printInt (arg3)
print (", arg4=")
printInt (arg4)
nl ()
*****/
switch syscallCodeNum
case SYSCALL_FORK:
return Handle_Sys_Fork ()
case SYSCALL_YIELD:
Handle_Sys_Yield ()
return 0
case SYSCALL_EXEC:
return Handle_Sys_Exec (arg1 asPtrTo array of char)
case SYSCALL_JOIN:
return Handle_Sys_Join (arg1)
case SYSCALL_EXIT:
Handle_Sys_Exit (arg1)
return 0
case SYSCALL_CREATE:
return Handle_Sys_Create (arg1 asPtrTo array of char)
case SYSCALL_OPEN:
return Handle_Sys_Open (arg1 asPtrTo array of char)
case SYSCALL_READ:
return Handle_Sys_Read (arg1, arg2 asPtrTo char, arg3)
case SYSCALL_WRITE:
return Handle_Sys_Write (arg1, arg2 asPtrTo char, arg3)
case SYSCALL_SEEK:
return Handle_Sys_Seek (arg1, arg2)
case SYSCALL_CLOSE:
Handle_Sys_Close (arg1)
return 0
case SYSCALL_SHUTDOWN:
Handle_Sys_Shutdown ()
return 0
default:
print ("Syscall code = ")
printInt (syscallCodeNum)
nl ()
FatalError ("Unknown syscall code from user thread")
endSwitch
return 0
endFunction
----------------------------- Handle_Sys_Exit ---------------------------------
function Handle_Sys_Exit (returnStatus: int)
-- NOT IMPLEMENTED
endFunction
----------------------------- Handle_Sys_Shutdown ---------------------------------
function Handle_Sys_Shutdown ()
-- NOT IMPLEMENTED
endFunction
----------------------------- Handle_Sys_Yield ---------------------------------
function Handle_Sys_Yield ()
-- NOT IMPLEMENTED
endFunction
----------------------------- Handle_Sys_Fork ---------------------------------
function Handle_Sys_Fork () returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Join ---------------------------------
function Handle_Sys_Join (processID: int) returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Exec ---------------------------------
function Handle_Sys_Exec (filename: ptr to array of char) returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Create ---------------------------------
function Handle_Sys_Create (filename: ptr to array of char) returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Open ---------------------------------
function Handle_Sys_Open (filename: ptr to array of char) returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Read ---------------------------------
function Handle_Sys_Read (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Write ---------------------------------
function Handle_Sys_Write (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Seek ---------------------------------
function Handle_Sys_Seek (fileDesc: int, newCurrentPos: int) returns int
-- NOT IMPLEMENTED
return 0
endFunction
----------------------------- Handle_Sys_Close ---------------------------------
function Handle_Sys_Close (fileDesc: int)
-- NOT IMPLEMENTED
endFunction
endCode
|
haominhe/Graduate
|
CS510 Operating System Foundations/P5/Kernel.c
|
code Kernel
-- <NAME>
-- References:
-- http://web.cecs.pdx.edu/~harry/Blitz/InstructorInfo/IdeasOnHoareTask.pdf
-- http://www.cs.utexas.edu/users/lorenzo/corsi/cs372h/07S/notes/Lecture12.pdf
-- https://cseweb.ucsd.edu/classes/sp16/cse120-a/applications/ln/lecture9.html
-- http://pages.cs.wisc.edu/~remzi/OSTEP/threads-monitors.pdf
-- https://github.com/tgjamin/
-- https://github.com/ladinu/
-- https://github.com/obriematt/
-- https://github.com/JuShuck/
----------------------------- InitializeScheduler ---------------------------------
function InitializeScheduler ()
--
-- This routine assumes that we are in System mode. It sets up the
-- thread scheduler and turns the executing program into "main-thread".
-- After exit, we can execute "Yield", "Fork", etc. Upon return, the
-- main-thread will be executing with interrupts enabled.
--
Cleari ()
print ("Initializing Thread Scheduler...\n")
readyList = new List [Thread]
threadsToBeDestroyed = new List [Thread]
mainThread = new Thread
mainThread.Init ("main-thread")
mainThread.status = RUNNING
idleThread = new Thread
idleThread.Init ("idle-thread")
idleThread.Fork (IdleFunction, 0)
currentThread = & mainThread
FatalError = FatalError_ThreadVersion -- Use a routine which prints threadname
currentInterruptStatus = ENABLED
Seti ()
endFunction
----------------------------- IdleFunction ---------------------------------
function IdleFunction (arg: int)
--
-- This is the "idle thread", a kernel thread which ensures that the ready
-- list is never empty. The idle thread constantly yields to other threads
-- in an infinite loop. However, before yielding, it first checks to see if
-- there are other threads. If there are no other threads, the idle thread
-- will execute the "wait" instruction. The "wait" instruction will enable
-- interrupts and halt CPU execution until the next interrupt arrives.
--
var junk: int
while true
junk = SetInterruptsTo (DISABLED)
if readyList.IsEmpty ()
Wait ()
else
currentThread.Yield ()
endIf
endWhile
endFunction
----------------------------- Run ---------------------------------
function Run (nextThread: ptr to Thread)
--
-- Begin executing the thread "nextThread", which has already
-- been removed from the readyList. The current thread will
-- be suspended; we assume that its status has already been
-- changed to READY or BLOCKED. We assume that interrupts are
-- DISABLED when called.
--
-- This routine is called only from "Thread.Yield" and "Thread.Sleep".
--
-- It is allowable for nextThread to be currentThread.
--
var prevThread, th: ptr to Thread
prevThread = currentThread
prevThread.CheckOverflow ()
-- If the previous thread was using the USER registers, save them.
if prevThread.isUserThread
SaveUserRegs (&prevThread.userRegs[0])
endIf
currentThread = nextThread
nextThread.status = RUNNING
--print ("SWITCHING from ")
--print (prevThread.name)
--print (" to ")
--print (nextThread.name)
--print ("\n")
Switch (prevThread, nextThread)
--print ("After SWITCH, back in thread ")
--print (currentThread.name)
--print ("\n")
while ! threadsToBeDestroyed.IsEmpty ()
th = threadsToBeDestroyed.Remove()
threadManager.FreeThread (th)
endWhile
-- If the new thread uses the USER registers, restore them.
if currentThread.isUserThread
RestoreUserRegs (¤tThread.userRegs[0])
currentThread.myProcess.addrSpace.SetToThisPageTable ()
endIf
endFunction
----------------------------- PrintReadyList ---------------------------------
function PrintReadyList ()
--
-- This routine prints the readyList. It disables interrupts during the
-- printing to guarantee that the readyList won't change while it is'
-- being printed, which could cause disaster in this routine!
--
var oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the ready list:\n")
readyList.ApplyToEach (ThreadPrintShort)
oldStatus = SetInterruptsTo (oldStatus)
endFunction
----------------------------- ThreadStartMain ---------------------------------
function ThreadStartMain ()
--
-- This function is called from the assembly language routine "ThreadStart"".
-- It is the first KPL code each thread will execute, and it will
-- invoke the thread's "main" function, with interrupts enabled. If the "main"
-- function ever returns, this function will terminate this thread. This
-- function will never return.
--
var
junk: int
mainFun: ptr to function (int)
-- print ("ThreadStartMain...\n")
junk = SetInterruptsTo (ENABLED)
mainFun = currentThread.initialFunction
mainFun (currentThread.initialArgument)
ThreadFinish ()
FatalError ("ThreadFinish should never return")
endFunction
----------------------------- ThreadFinish ---------------------------------
function ThreadFinish ()
--
-- As the last thing to do in this thread, we want to clean up
-- and reclaim the Thread object. This method is called as the
-- last thing the thread does; this is the normal way for a thread
-- to die. However, since the thread is still running in this,
-- we can't actually do the clean up. So we just make a note
-- that it is pending. After the next thread starts (in method "Run")
-- we'll finish the job.
--
var junk: int
junk = SetInterruptsTo (DISABLED)
-- print ("Finishing ")
-- print (currentThread.name)
-- print ("\n")
threadsToBeDestroyed.AddToEnd (currentThread)
currentThread.Sleep ()
-- Execution will never reach the next instruction
FatalError ("This thread will never run again")
endFunction
----------------------------- FatalError_ThreadVersion -----------------------
function FatalError_ThreadVersion (errorMessage: ptr to array of char)
--
-- This function will print out the name of the current thread and
-- the given error message. Then it will call "RuntimeExit" to
-- shutdown the system.
--
var
junk: int
junk = SetInterruptsTo (DISABLED)
print ("\nFATAL ERROR")
if currentThread -- In case errors occur before thread initialization
print (" in ")
print (currentThread.name)
endIf
print (": \"")
print (errorMessage)
print ("\" -- TERMINATING!\n\n")
print ("(To find out where execution was when the problem arose, type 'st' at the emulator prompt.)\n")
RuntimeExit ()
endFunction
----------------------------- SetInterruptsTo ---------------------------------
function SetInterruptsTo (newStatus: int) returns int
--
-- This routine is passed a status (DISABLED or ENABLED). It
-- returns the previous interrupt status and sets the interrupt
-- status to "newStatus".
--
-- Since this routine reads and modifies a shared variable
-- (currentInterruptStatus), there is a danger of this routine
-- being re-entered. Therefore, it momentarily will disable
-- interrupts, to ensure a valid update to this variable.
--
var
oldStat: int
Cleari ()
oldStat = currentInterruptStatus
if newStatus == ENABLED
currentInterruptStatus = ENABLED
Seti ()
else
currentInterruptStatus = DISABLED
Cleari ()
endIf
return oldStat
endFunction
----------------------------- Semaphore ---------------------------------
behavior Semaphore
-- This class provides the following methods:
-- Up() ...also known as "V" or "Signal"...
-- Increment the semaphore count. Wake up a thread if
-- there are any waiting. This operation always executes
-- quickly and will not suspend the thread.
-- Down() ...also known as "P" or "Wait"...
-- Decrement the semaphore count. If the count would go
-- negative, wait for some other thread to do an Up()
-- first. Conceptually, the count will never go negative.
-- Init(initialCount)
-- Each semaphore must be initialized. Normally, you should
-- invoke this method, providing an 'initialCount' of zero.
-- If the semaphore is initialized with 0, then a Down()
-- operation before any Up() will wait for the first
-- Up(). If initialized with i, then it is as if i Up()
-- operations have been performed already.
--
-- NOTE: The user should never look at a semaphore's count since the value
-- retrieved may be out-of-date, due to other threads performing Up() or
-- Down() operations since the retrieval of the count.'
---------- Semaphore . Init ----------
method Init (initialCount: int)
if initialCount < 0
FatalError ("Semaphore created with initialCount < 0")
endIf
count = initialCount
waitingThreads = new List [Thread]
endMethod
---------- Semaphore . Up ----------
method Up ()
var
oldIntStat: int
t: ptr to Thread
oldIntStat = SetInterruptsTo (DISABLED)
if count == 0x7fffffff
FatalError ("Semaphore count overflowed during 'Up' operation")
endIf
count = count + 1
if count <= 0
t = waitingThreads.Remove ()
t.status = READY
readyList.AddToEnd (t)
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
---------- Semaphore . Down ----------
method Down ()
var
oldIntStat: int
oldIntStat = SetInterruptsTo (DISABLED)
if count == 0x80000000
FatalError ("Semaphore count underflowed during 'Down' operation")
endIf
count = count - 1
if count < 0
waitingThreads.AddToEnd (currentThread)
currentThread.Sleep ()
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
endBehavior
----------------------------- Mutex ---------------------------------
behavior Mutex
-- This class provides the following methods:
-- Lock()
-- Acquire the mutex if free, otherwise wait until the mutex is
-- free and then get it.
-- Unlock()
-- Release the mutex. If other threads are waiting, then
-- wake up the oldest one and give it the lock.
-- Init()
-- Each mutex must be initialized.
-- IsHeldByCurrentThread()
-- Return TRUE iff the current (invoking) thread holds a lock
-- on the mutex.
----------- Mutex . Init -----------
method Init ()
waitingThreads = new List [Thread]
endMethod
----------- Mutex . Lock -----------
method Lock ()
var
oldIntStat: int
if heldBy == currentThread
FatalError ("Attempt to lock a mutex by a thread already holding it")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
if !heldBy
heldBy = currentThread
else
waitingThreads.AddToEnd (currentThread)
currentThread.Sleep ()
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
----------- Mutex . Unlock -----------
method Unlock ()
var
oldIntStat: int
t: ptr to Thread
if heldBy != currentThread
FatalError ("Attempt to unlock a mutex by a thread not holding it")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
t = waitingThreads.Remove ()
if t
t.status = READY
readyList.AddToEnd (t)
heldBy = t
else
heldBy = null
endIf
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
----------- Mutex . IsHeldByCurrentThread -----------
method IsHeldByCurrentThread () returns bool
return heldBy == currentThread
endMethod
endBehavior
----------------------------- Condition ---------------------------------
behavior Condition
-- This class is used to implement monitors. Each monitor will have a
-- mutex lock and one or more condition variables. The lock ensures that
-- only one process at a time may execute code in the monitor. Within the
-- monitor code, a thread can execute Wait() and Signal() operations
-- on the condition variables to make sure certain condions are met.
--
-- The condition variables here implement "Mesa-style" semantics, which
-- means that in the time between a Signal() operation and the awakening
-- and execution of the corrsponding waiting thread, other threads may
-- have snuck in and run. The waiting thread should always re-check the
-- data to ensure that the condition which was signalled is still true.
--
-- This class provides the following methods:
-- Wait(mutex)
-- This method assumes the mutex has alreasy been locked.
-- It unlocks it, and goes to sleep waiting for a signal on
-- this condition. When the signal is received, this method
-- re-awakens, re-locks the mutex, and returns.
-- Signal(mutex)
-- If there are any threads waiting on this condition, this
-- method will wake up the oldest and schedule it to run.
-- However, since this thread holds the mutex and never unlocks
-- it, the newly awakened thread will be forced to wait before
-- it can re-acquire the mutex and resume execution.
-- Broadcast(mutex)
-- This method is like Signal() except that it wakes up all
-- threads waiting on this condition, not just the next one.
-- Init()
-- Each condition must be initialized.
---------- Condition . Init ----------
method Init ()
waitingThreads = new List [Thread]
endMethod
---------- Condition . Wait ----------
method Wait (mutex: ptr to Mutex)
var
oldIntStat: int
if ! mutex.IsHeldByCurrentThread ()
FatalError ("Attempt to wait on condition when mutex is not held")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
mutex.Unlock ()
waitingThreads.AddToEnd (currentThread)
currentThread.Sleep ()
-- no need to lock the mutex, no need to wait for the next thread to acquire it
-- because we hand the lock off directly to the next thread
mutex.Lock ()
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
---------- Condition . Signal ----------
-- The code we have given you for the Signal method in the Condition class uses MESA
-- semantics. Change the implementation so that it uses Hoare semantics.
method Signal (mutex: ptr to Mutex)
var
oldIntStat: int
t: ptr to Thread
if ! mutex.IsHeldByCurrentThread ()
FatalError ("Attempt to signal a condition when mutex is not held")
endIf
-- disable interrupts, so that other threads cannot intervene the handing off lock process
oldIntStat = SetInterruptsTo (DISABLED)
t = waitingThreads.Remove ()
--mutex.heldBy = t -- handoff the lock to next thread in list for Hoare semantics
if t
t.status = READY
readyList.AddToEnd (t)
endIf
--mutex.Lock() -- give the lock to the next waking up thread
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
---------- Condition . Broadcast ----------
method Broadcast (mutex: ptr to Mutex)
var
oldIntStat: int
t: ptr to Thread
if ! mutex.IsHeldByCurrentThread ()
FatalError ("Attempt to broadcast a condition when lock is not held")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
while true
t = waitingThreads.Remove ()
if t == null
break
endIf
t.status = READY
readyList.AddToEnd (t)
endWhile
oldIntStat = SetInterruptsTo (oldIntStat)
endMethod
endBehavior
----------------------------- Thread ---------------------------------
behavior Thread
---------- Thread . Init ----------
method Init (n: String)
--
-- Initialize this Thread object, but do not schedule it for
-- execution yet.
--
name = n
status = JUST_CREATED
-- The next line initializes the systemStack array, without filling it in.
*((& systemStack) asPtrTo int) = SYSTEM_STACK_SIZE
systemStack [0] = STACK_SENTINEL
systemStack [SYSTEM_STACK_SIZE-1] = STACK_SENTINEL
stackTop = & (systemStack[SYSTEM_STACK_SIZE-1])
regs = new array of int { 13 of 0 }
isUserThread = false
userRegs = new array of int { 15 of 0 }
endMethod
---------- Thread . Fork ----------
method Fork (fun: ptr to function (int), arg: int)
--
-- This method will schedule this thread for execution; in other words
-- it will make it ready to run by adding it to the "ready queue." This
-- method is passed a function and a single integer argument. When the
-- thread runs, the thread will execute this function on that argument
-- and then termiante. This method will return after scheduling this
-- thread.
--
var
oldIntStat, junk: int
oldIntStat = SetInterruptsTo (DISABLED)
-- print ("Forking thread...\n")
initialFunction = fun
initialArgument = arg
stackTop = stackTop - 4
*(stackTop asPtrTo int) = ThreadStartUp asInteger
status = READY
readyList.AddToEnd (self)
junk = SetInterruptsTo (oldIntStat)
endMethod
---------- Thread . Yield ----------
method Yield ()
--
-- This method should only be invoked on the current thread. The
-- current thread may yield the processor to other threads by
-- executing:
-- currentThread.Yield ()
-- This method may be invoked with or without interrupts enabled.
-- Upon return, the interrupts will be in the same state; however
-- since other threads are given a chance to run and they may allow
-- interrupts, interrupts handlers may have been invoked before
-- this method returns.
--
var
nextTh: ptr to Thread
oldIntStat, junk: int
-- ASSERT:
if self != currentThread
FatalError ("In Yield, self != currentThread")
endIf
oldIntStat = SetInterruptsTo (DISABLED)
-- print ("Yielding ")
-- print (name)
-- print ("\n")
nextTh = readyList.Remove ()
if nextTh
-- print ("About to run ")
-- print (nextTh.name)
-- print ("\n")
if status == BLOCKED
FatalError ("Status of current thread should be READY or RUNNING")
endIf
status = READY
readyList.AddToEnd (self)
Run (nextTh)
endIf
junk = SetInterruptsTo (oldIntStat)
endMethod
---------- Thread . Sleep ----------
method Sleep ()
--
-- This method should only be invoked on the current thread. It
-- will set the status of the current thread to BLCOKED and will
-- will switch to executing another thread. It is assumed that
-- (1) Interrupts are disabled before calling this routine, and
-- (2) The current thread has been placed on some other wait
-- list (e.g., for a Semaphore) or else the thread will
-- never get scheduled again.
--
var nextTh: ptr to Thread
-- ASSERT:
if currentInterruptStatus != DISABLED
FatalError ("In Sleep, currentInterruptStatus != DISABLED")
endIf
-- ASSERT:
if self != currentThread
FatalError ("In Sleep, self != currentThread")
endIf
-- print ("Sleeping ")
-- print (name)
-- print ("\n")
status = BLOCKED
nextTh = readyList.Remove ()
if nextTh == null
FatalError ("Ready list should always contain the idle thread")
endIf
Run (nextTh)
endMethod
---------- Thread . CheckOverflow ----------
method CheckOverflow ()
--
-- This method checks to see if this thread has overflowed its
-- pre-alloted stack space. WARNING: the approach taken here is only
-- guaranteed to work "with high probability".
--
if systemStack[0] != STACK_SENTINEL
FatalError ("System stack overflow detected!")
elseIf systemStack[SYSTEM_STACK_SIZE-1] != STACK_SENTINEL
FatalError ("System stack underflow detected!")
endIf
endMethod
---------- Thread . Print ----------
method Print ()
--
-- Print this object.
--
var i: int
oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print (" Thread \"")
print (name)
print ("\" (addr of Thread object: ")
printHex (self asInteger)
print (")\n")
print (" machine state:\n")
for i = 0 to 12
print (" r")
printInt (i+2)
print (": ")
printHex (regs[i])
print (" ")
printInt (regs[i])
print ("\n")
endFor
printHexVar (" stackTop", stackTop asInteger)
printHexVar (" stack starting addr", (& systemStack[0]) asInteger)
switch status
case JUST_CREATED:
print (" status = JUST_CREATED\n")
break
case READY:
print (" status = READY\n")
break
case RUNNING:
print (" status = RUNNING\n")
break
case BLOCKED:
print (" status = BLOCKED\n")
break
case UNUSED:
print (" status = UNUSED\n")
break
default:
FatalError ("Bad status in Thread")
endSwitch
print (" is user thread: ")
printBool (isUserThread)
nl ()
print (" user registers:\n")
for i = 0 to 14
print (" r")
printInt (i+1)
print (": ")
printHex (userRegs[i])
print (" ")
printInt (userRegs[i])
print ("\n")
endFor
oldStatus = SetInterruptsTo (oldStatus)
endMethod
endBehavior
----------------------------- ThreadPrintShort ---------------------------------
function ThreadPrintShort (t: ptr to Thread)
--
-- This function prints a single line giving the name of thread "t",
-- its status, and the address of the Thread object itself (which may be
-- helpful in distinguishing Threads when the name is not helpful).
--
var
oldStatus: int = SetInterruptsTo (DISABLED)
if !t
print ("NULL\n")
return
endIf
print (" Thread \"")
print (t.name)
print ("\" status=")
switch t.status
case JUST_CREATED:
print ("JUST_CREATED")
break
case READY:
print ("READY")
break
case RUNNING:
print ("RUNNING")
break
case BLOCKED:
print ("BLOCKED")
break
case UNUSED:
print ("UNUSED")
break
default:
FatalError ("Bad status in Thread")
endSwitch
print (" (addr of Thread object: ")
printHex (t asInteger)
print (")")
nl ()
-- t.Print ()
oldStatus = SetInterruptsTo (oldStatus)
endFunction
----------------------------- ThreadManager ---------------------------------
behavior ThreadManager
---------- ThreadManager . Init ----------
method Init ()
--
-- This method is called once at kernel startup time to initialize
-- the one and only "ThreadManager" object.
-- Top level language, declare variables at the top of the function
var
counter: int
print ("Initializing Thread Manager...\n")
-- IMPLEMENTED
-- initialize the array of threads -> initialize each thread in the array ->
-- set its status to UNUSED
threadTable = new array of Thread {MAX_NUMBER_OF_PROCESSES of new Thread}
freeList = new List [Thread]
-- a counter to loop through threadTable and modify corrsponding elements
for counter=0 to MAX_NUMBER_OF_PROCESSES - 1
threadTable[counter].Init("threadManager thread")
threadTable[counter].status = UNUSED
-- initialize the freeList -> place all Threads in the threadTable array
-- on the freeList during initialization
-- pass the address of current thread to list, instead of passing the actual thread object
freeList.AddToEnd(&threadTable[counter])
endFor
-- initialize the monitor lock and condition variable
threadManagerLock = new Mutex
threadManagerLock.Init()
aThreadBecameFree = new Condition
aThreadBecameFree.Init()
endMethod
---------- ThreadManager . Print ----------
method Print ()
--
-- Print each thread. Since we look at the freeList, this
-- routine disables interrupts so the printout will be a
-- consistent snapshot of things.
--
var i, oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the thread table...\n")
for i = 0 to MAX_NUMBER_OF_PROCESSES-1
print (" ")
printInt (i)
print (":")
ThreadPrintShort (&threadTable[i])
endFor
print ("Here is the FREE list of Threads:\n ")
freeList.ApplyToEach (PrintObjectAddr)
nl ()
oldStatus = SetInterruptsTo (oldStatus)
endMethod
---------- ThreadManager . GetANewThread ----------
method GetANewThread () returns ptr to Thread
--
-- This method returns a new Thread; it will wait
-- until one is available.
-- if we have free thread slot in the freeList, we hand it to the caller who wants a thread
-- return a local variable pointer, initialize to null
var temp : ptr to Thread
temp = null
-- IMPLEMENTED
-- GetANewThread is an entry method -> must obtain the
-- monitor lock in the first statement and release it in the last statement
threadManagerLock.Lock()
-- If the freeList is empty, this method will need to wait on the condition
-- of a thread becoming available.
-- use while for MESA, use if for Hoare semantics
while freeList.IsEmpty()
aThreadBecameFree.Wait(&threadManagerLock)
endWhile
--if freeList.IsEmpty()
--aThreadBecameFree.Wait(&threadManagerLock)
--endIf
-- If there are avaiable threads, GetANewThread will remove and return a Thread
-- from the freeList.
temp = freeList.Remove() -- get the pointer to the current thread
-- change the Thread status to JUST_CREATED
temp.status = JUST_CREATED
threadManagerLock.Unlock()
return temp
endMethod
---------- ThreadManager . FreeThread ----------
method FreeThread (th: ptr to Thread)
--
-- This method is passed a ptr to a Thread; It moves it
-- to the FREE list.
-- Every thread that terminates will be added back to the freeList
-- IMPLEMENTED
-- FreeThread is an entry method -> must obtain the
-- monitor lock in the first statement and release it in the last statement
threadManagerLock.Lock()
-- The FreeThread method will add a Thread back to the freeList and
-- signal anyone waiting on the condition
-- change the Thread status to UNUSED
th.status = UNUSED
freeList.AddToEnd(th)
aThreadBecameFree.Signal(&threadManagerLock)
threadManagerLock.Unlock()
endMethod
endBehavior
-------------------------- ProcessControlBlock ------------------------------
behavior ProcessControlBlock
---------- ProcessControlBlock . Init ----------
--
-- This method is called once for every PCB at startup time.
--
method Init ()
pid = -1
status = FREE
addrSpace = new AddrSpace
addrSpace.Init ()
-- Uncomment this code later...
/*
fileDescriptor = new array of ptr to OpenFile
{ MAX_FILES_PER_PROCESS of null }
*/
endMethod
---------- ProcessControlBlock . Print ----------
method Print ()
--
-- Print this ProcessControlBlock using several lines.
--
-- var i: int
self.PrintShort ()
addrSpace.Print ()
print (" myThread = ")
ThreadPrintShort (myThread)
-- Uncomment this code later...
/*
print (" File Descriptors:\n")
for i = 0 to MAX_FILES_PER_PROCESS-1
if fileDescriptor[i]
fileDescriptor[i].Print ()
endIf
endFor
*/
nl ()
endMethod
---------- ProcessControlBlock . PrintShort ----------
method PrintShort ()
--
-- Print this ProcessControlBlock on one line.
--
print (" ProcessControlBlock (addr=")
printHex (self asInteger)
print (") pid=")
printInt (pid)
print (", status=")
if status == ACTIVE
print ("ACTIVE")
elseIf status == ZOMBIE
print ("ZOMBIE")
elseIf status == FREE
print ("FREE")
else
FatalError ("Bad status in ProcessControlBlock")
endIf
print (", parentsPid=")
printInt (parentsPid)
print (", exitStatus=")
printInt (exitStatus)
nl ()
endMethod
endBehavior
----------------------------- ProcessManager ---------------------------------
behavior ProcessManager
---------- ProcessManager . Init ----------
method Init ()
--
-- This method is called once at kernel startup time to initialize
-- the one and only "processManager" object.
-- these are resources which must be allocated. This is the purpose of the monitor
-- class called ProcessManager
-- IMPLEMENTED
var counter : int
processTable = new array of ProcessControlBlock {MAX_NUMBER_OF_PROCESSES of new ProcessControlBlock}
-- freeList is a list of all ProcessControlBlocks that are FREE
freeList = new List [ProcessControlBlock]
-- The status of a ProcessControlBlock should be FREE if and only
-- if it is on the freeList.
-- initialize all the ProcessControlBlocks in processTable array
for counter=0 to MAX_NUMBER_OF_PROCESSES - 1
processTable[counter].Init()
-- we should set status to FREE since we added it to the freeList
processTable[counter].status = FREE
-- pass the address of current ProcessControlBlock to list
freeList.AddToEnd(& processTable[counter])
endFor
-- we will ignore the ZOMBIE state. Every process will be either ACTIVE or
-- FREE. ignore aProcessDied, but should be initialized nonetheless.
processManagerLock = new Mutex -- These synchronization objects
processManagerLock.Init()
aProcessBecameFree = new Condition -- apply to the "freeList"
aProcessBecameFree.Init()
-- aProcessDied is signaled when a process goes from ACTIVE to ZOMBIE
aProcessDied = new Condition
aProcessDied.Init()
-- Each process will have a unique process ID (the field named pid).
nextPid = 0
endMethod
---------- ProcessManager . Print ----------
method Print ()
--
-- Print all processes. Since we look at the freeList, this
-- routine disables interrupts so the printout will be a
-- consistent snapshot of things.
--
var i, oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the process table...\n")
for i = 0 to MAX_NUMBER_OF_PROCESSES-1
print (" ")
printInt (i)
print (":")
processTable[i].Print ()
endFor
print ("Here is the FREE list of ProcessControlBlocks:\n ")
freeList.ApplyToEach (PrintObjectAddr)
nl ()
oldStatus = SetInterruptsTo (oldStatus)
endMethod
---------- ProcessManager . PrintShort ----------
method PrintShort ()
--
-- Print all processes. Since we look at the freeList, this
-- routine disables interrupts so the printout will be a
-- consistent snapshot of things.
--
var i, oldStatus: int
oldStatus = SetInterruptsTo (DISABLED)
print ("Here is the process table...\n")
for i = 0 to MAX_NUMBER_OF_PROCESSES-1
print (" ")
printInt (i)
processTable[i].PrintShort ()
endFor
print ("Here is the FREE list of ProcessControlBlocks:\n ")
freeList.ApplyToEach (PrintObjectAddr)
nl ()
oldStatus = SetInterruptsTo (oldStatus)
endMethod
---------- ProcessManager . GetANewProcess ----------
method GetANewProcess () returns ptr to ProcessControlBlock
--
-- This method returns a new ProcessControlBlock; it will wait
-- until one is available.
-- In our kernel, each user-level process will contain only one thread.
-- return a local variable pointer, initialize to null
var temp : ptr to ProcessControlBlock
temp = null
-- IMPLEMENTED
-- several threads may simultaneously request a new ProcessControlBlock by calling
-- GetANewProcess. The ProcessManager is a “monitor,” in order to protect the
-- freeList from concurrent access -> use Mutex
processManagerLock.Lock()
-- If the freeList is empty, wait on the condition of a ProcessControlBlock becoming availiable
-- use while for MESA, use if for Hoare semantics
while freeList.IsEmpty()
aProcessBecameFree.Wait(& processManagerLock)
endWhile
--if freeList.IsEmpty()
--aProcessBecameFree.Wait(& processManagerLock)
--endIf
-- If there are avaiable threads, remove and return a ProcessControlBlock from the freeList
temp = freeList.Remove() -- get the pointer to the current ProcessControlBlock
-- change the ProcessControlBlock to ACTIVE
temp.status = ACTIVE
-- Every time a ProcessControlBlock is allocated
-- this integer must be incremented and used to set the process’s pid
nextPid = nextPid + 1
-- assign a process ID to this ProcessControlBlock
temp.pid = nextPid
processManagerLock.Unlock()
return temp
endMethod
---------- ProcessManager . FreeProcess ----------
method FreeProcess (p: ptr to ProcessControlBlock)
--
-- This method is passed a ptr to a Process; It moves it
-- to the FREE list.
-- Both GetANewProcess and FreeProcess are monitor entry methods
-- IMPLEMENTED
processManagerLock.Lock()
-- When a ProcessControlBlock is added to the freeList, the condition aProcessBecameFree
-- can be Signaled to wake up any thread waiting for a ProcessControlBlock.
-- we should set status to FREE since we added it to the freeList
p.status = FREE
freeList.AddToEnd(p)
aProcessBecameFree.Signal(& processManagerLock)
processManagerLock.Unlock()
endMethod
endBehavior
----------------------------- PrintObjectAddr ---------------------------------
function PrintObjectAddr (p: ptr to Object)
--
-- Print the address of the given object.
--
printHex (p asInteger)
printChar (' ')
endFunction
----------------------------- ProcessFinish --------------------------
function ProcessFinish (exitStatus: int)
--
-- This routine is called when a process is to be terminated. It will
-- free the resources held by this process and will terminate the
-- current thread.
--
FatalError ("ProcessFinish is not implemented")
endFunction
----------------------------- FrameManager ---------------------------------
behavior FrameManager
---------- FrameManager . Init ----------
method Init ()
--
-- This method is called once at kernel startup time to initialize
-- the one and only "frameManager" object.
--
var i: int
print ("Initializing Frame Manager...\n")
framesInUse = new BitMap
framesInUse.Init (NUMBER_OF_PHYSICAL_PAGE_FRAMES)
numberFreeFrames = NUMBER_OF_PHYSICAL_PAGE_FRAMES
frameManagerLock = new Mutex
frameManagerLock.Init ()
newFramesAvailable = new Condition
newFramesAvailable.Init ()
-- Check that the area to be used for paging contains zeros.
-- The BLITZ emulator will initialize physical memory to zero, so
-- if by chance the size of the kernel has gotten so large that
-- it runs into the area reserved for pages, we will detect it.
-- Note: this test is not 100%, but is included nonetheless.
for i = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME
to PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME+300
by 4
if 0 != *(i asPtrTo int)
FatalError ("Kernel code size appears to have grown too large and is overflowing into the frame region")
endIf
endFor
endMethod
---------- FrameManager . Print ----------
method Print ()
--
-- Print which frames are allocated and how many are free.
--
frameManagerLock.Lock ()
print ("FRAME MANAGER:\n")
printIntVar (" numberFreeFrames", numberFreeFrames)
print (" Here are the frames in use: \n ")
framesInUse.Print ()
frameManagerLock.Unlock ()
endMethod
---------- FrameManager . GetAFrame ----------
method GetAFrame () returns int
--
-- Allocate a single frame and return its physical address. If no frames
-- are currently available, wait until the request can be completed.
--
var f, frameAddr: int
-- Acquire exclusive access to the frameManager data structure...
frameManagerLock.Lock ()
-- Wait until we have enough free frames to entirely satisfy the request...
while numberFreeFrames < 1
newFramesAvailable.Wait (&frameManagerLock)
endWhile
-- Find a free frame and allocate it...
f = framesInUse.FindZeroAndSet ()
numberFreeFrames = numberFreeFrames - 1
-- Unlock...
frameManagerLock.Unlock ()
-- Compute and return the physical address of the frame...
frameAddr = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME + (f * PAGE_SIZE)
-- printHexVar ("GetAFrame returning frameAddr", frameAddr)
return frameAddr
endMethod
---------- FrameManager . GetNewFrames ----------
method GetNewFrames (aPageTable: ptr to AddrSpace, numFramesNeeded: int)
-- 2^13 = 8192
-- Each frame is a resource. a thread will request some frames; the frameManager
-- will either be able to satisfy the request, or the requesting thread will have
-- to wait until the request can be satisfied.
-- IMPLEMENTED
var i , f , frameAddr : int
-- Acquire the frame manager lock.
frameManagerLock.Lock ()
-- GetANewFrame allocates one frame (waiting until at least one is available) and
-- returns the address of the frame.
-- Wait on newFramesAvailable until there are enough free frames to satisfy the request.
-- while for MESA, if for Hoare
while numberFreeFrames < numFramesNeeded
newFramesAvailable.Wait (&frameManagerLock)
endWhile
--if numberFreeFrames < numFramesNeeded
--newFramesAvailable.Wait (&frameManagerLock)
--endIf
-- Do a loop for each of the frames
for i = 0 to numFramesNeeded-1
-- determine which frame is free (find and set a bit in the framesInUse BitMap)
-- Find a free frame and allocate it...
f = framesInUse.FindZeroAndSet ()
-- figure out the address of the free frame
-- Compute the physical address of the frame...
frameAddr = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME + (f * PAGE_SIZE)
-- When the frames are gotten, the GetNewFrames method needs to make a note of which
-- frames have been allocated. It does this by storing the address of each frame it
-- allocates (the address of the first byte in each frame) into an AddrSpace object
-- An AddrSpace object is used to represent a virtual address space and to tell where
-- in physical memory the virtual pages are actually located.
-- aPageTable : ptr to AddrSpace
-- to store the address of the frame which has been allocated
aPageTable.SetFrameAddr (i, frameAddr)
-- Adjust the number of free frames
numberFreeFrames = numberFreeFrames - 1
endFor
-- Set aPageTable.numberOfPages to the number of frames allocated
aPageTable.numberOfPages = aPageTable.numberOfPages + i
-- Unlock the frame manager
frameManagerLock.Unlock ()
endMethod
---------- FrameManager . ReturnAllFrames ----------
method ReturnAllFrames (aPageTable: ptr to AddrSpace)
-- there is never a need to return frames one at a time
-- IMPLEMENTED
var i, frameAddr, bitNumber : int
-- Acquire the frame manager lock.
frameManagerLock.Lock ()
-- It can look at aPageTable.numberOfPages to see how many are being returned.
-- It can then go through the page table and see which frames it possessed. For each,
-- it can clear the bit.
for i = 0 to aPageTable.numberOfPages - 1
frameAddr = aPageTable.ExtractFrameAddr (i)
-- do the opposite calculation
-- frameAddr = PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME + (f * PAGE_SIZE)
bitNumber = (frameAddr - PHYSICAL_ADDRESS_OF_FIRST_PAGE_FRAME) / PAGE_SIZE
framesInUse.ClearBit(bitNumber)
numberFreeFrames = numberFreeFrames + 1
newFramesAvailable.Signal(&frameManagerLock)
endFor
-- adjust the number of free frames and “notify” any waiting threads that more frames
-- have become available.
-- The thread that gets awakened may not have enough free frames to complete, but other
-- waiting threads may be able to proceed.
-- newFramesAvailable.Broadcast(&frameManagerLock)
aPageTable.numberOfPages = aPageTable.numberOfPages - i
-- Unlock the frame manager
frameManagerLock.Unlock ()
endMethod
endBehavior
----------------------------- AddrSpace ---------------------------------
behavior AddrSpace
---------- AddrSpace . Init ----------
method Init ()
--
-- Initialize this object.
--
numberOfPages = 0
pageTable = new array of int { MAX_PAGES_PER_VIRT_SPACE of 0x00000003 }
endMethod
---------- AddrSpace . Print ----------
method Print ()
--
-- Print this object.
--
var i: int
print (" addr entry Logical Physical Undefined Bits Dirty Referenced Writeable Valid\n")
print (" ========== ========== ========== ========== ============== ===== ========== ========= =====\n")
for i = 0 to numberOfPages-1
print (" ")
printHex ((&pageTable[i]) asInteger)
print (": ")
printHex (pageTable[i])
print (" ")
printHex (i * PAGE_SIZE) -- Logical address
print (" ")
printHex (self.ExtractFrameAddr (i)) -- Physical address
print (" ")
if self.ExtractUndefinedBits (i) != 0
printHex (self.ExtractUndefinedBits (i))
else
print (" ")
endIf
print (" ")
if self.IsDirty (i)
print ("YES")
else
print (" ")
endIf
print (" ")
if self.IsReferenced (i)
print ("YES")
else
print (" ")
endIf
print (" ")
if self.IsWritable (i)
print ("YES")
else
print (" ")
endIf
print (" ")
if self.IsValid (i)
print ("YES")
else
print (" ")
endIf
nl ()
endFor
endMethod
---------- AddrSpace . ExtractFrameAddr ----------
method ExtractFrameAddr (entry: int) returns int
--
-- Return the physical address of the frame in the selected page
-- table entry.
--
return (pageTable[entry] & 0xffffe000)
endMethod
---------- AddrSpace . ExtractUndefinedBits ----------
method ExtractUndefinedBits (entry: int) returns int
--
-- Return the undefined bits in the selected page table entry.
--
return (pageTable[entry] & 0x00001ff0)
endMethod
---------- AddrSpace . SetFrameAddr ----------
method SetFrameAddr (entry: int, frameAddr: int)
--
-- Set the physical address of the frame in the selected page
-- table entry to the value of the argument "frameAddr".
--
pageTable[entry] = (pageTable[entry] & 0x00001fff) | frameAddr
endMethod
---------- AddrSpace . IsDirty ----------
method IsDirty (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "dirty".
--
return (pageTable[entry] & 0x00000008) != 0
endMethod
---------- AddrSpace . IsReferenced ----------
method IsReferenced (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "referenced".
--
return (pageTable[entry] & 0x00000004) != 0
endMethod
---------- AddrSpace . IsWritable ----------
method IsWritable (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "writable".
--
return (pageTable[entry] & 0x00000002) != 0
endMethod
---------- AddrSpace . IsValid ----------
method IsValid (entry: int) returns bool
--
-- Return true if the selected page table entry is marked "valid".
--
return (pageTable[entry] & 0x00000001) != 0
endMethod
---------- AddrSpace . SetDirty ----------
method SetDirty (entry: int)
--
-- Set the selected page table entry's "dirty" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000008
endMethod
---------- AddrSpace . SetReferenced ----------
method SetReferenced (entry: int)
--
-- Set the selected page table entry's "referenced" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000004
endMethod
---------- AddrSpace . SetWritable ----------
method SetWritable (entry: int)
--
-- Set the selected page table entry's "writable" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000002
endMethod
---------- AddrSpace . SetValid ----------
method SetValid (entry: int)
--
-- Set the selected page table entry's "valid" bit to 1.
--
pageTable[entry] = pageTable[entry] | 0x00000001
endMethod
---------- AddrSpace . ClearDirty ----------
method ClearDirty (entry: int)
--
-- Clear the selected page table entry's "dirty" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000008
endMethod
---------- AddrSpace . ClearReferenced ----------
method ClearReferenced (entry: int)
--
-- Clear the selected page table entry's "referenced" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000004
endMethod
---------- AddrSpace . ClearWritable ----------
method ClearWritable (entry: int)
--
-- Clear the selected page table entry's "writable" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000002
endMethod
---------- AddrSpace . ClearValid ----------
method ClearValid (entry: int)
--
-- Clear the selected page table entry's "valid" bit.
--
pageTable[entry] = pageTable[entry] & ! 0x00000001
endMethod
---------- AddrSpace . SetToThisPageTable ----------
method SetToThisPageTable ()
--
-- This method sets the page table registers in the CPU to
-- point to this page table. Later, when paging is enabled,
-- this will become the active virtual address space.
--
LoadPageTableRegs ((& pageTable[0]) asInteger, numberOfPages*4)
endMethod
---------- AddrSpace . CopyBytesFromVirtual ----------
method CopyBytesFromVirtual (kernelAddr, virtAddr, numBytes: int)
returns int
--
-- This method copies data from a user's virtual address space
-- to somewhere in the kernel space. We assume that the
-- pages of the virtual address space are resident in
-- physical page frames. This routine returns the number of bytes
-- that were copied; if there was any problem with the virtual
-- addressed data, it returns -1.
--
var copiedSoFar, virtPage, offset, fromAddr: int
-- print ("CopyBytesFromVirtual called...\n")
-- printHexVar (" kernelAddr", kernelAddr)
-- printHexVar (" virtAddr", virtAddr)
-- printIntVar (" numBytes", numBytes)
if numBytes == 0
return 0
elseIf numBytes < 0
return -1
endIf
virtPage = virtAddr / PAGE_SIZE
offset = virtAddr % PAGE_SIZE
-- printHexVar (" virtPage", virtPage)
-- printHexVar (" offset", offset)
while true
if virtPage >= numberOfPages
print (" Virtual page number is too large!!!\n")
return -1
endIf
if ! self.IsValid (virtPage)
print (" Virtual page is not marked VALID!!!\n")
return -1
endIf
fromAddr = self.ExtractFrameAddr (virtPage) + offset
-- printHexVar (" Copying bytes from physcial addr", fromAddr)
while offset < PAGE_SIZE
-- printHexVar (" Copying a byte to physcial addr", kernelAddr)
-- printChar (* (fromAddr asPtrTo char))
* (kernelAddr asPtrTo char) = * (fromAddr asPtrTo char)
offset = offset + 1
kernelAddr = kernelAddr + 1
fromAddr = fromAddr + 1
copiedSoFar = copiedSoFar + 1
if copiedSoFar == numBytes
return copiedSoFar
endIf
endWhile
virtPage = virtPage + 1
offset = 0
endWhile
endMethod
---------- AddrSpace . CopyBytesToVirtual ----------
method CopyBytesToVirtual (virtAddr, kernelAddr, numBytes: int)
returns int
--
-- This method copies data from the kernel's address space to
-- somewhere in the virtual address space. We assume that the
-- pages of the virtual address space are resident in physical
-- page frames. This routine returns the number of bytes
-- that were copied; if there was any problem with the virtual
-- addressed data, it returns -1.
--
var copiedSoFar, virtPage, offset, destAddr: int
if numBytes == 0
return 0
elseIf numBytes < 0
return -1
endIf
virtPage = virtAddr / PAGE_SIZE
offset = virtAddr % PAGE_SIZE
while true
if (virtPage >= numberOfPages) ||
(! self.IsValid (virtPage)) ||
(! self.IsWritable (virtPage))
return -1
endIf
destAddr = self.ExtractFrameAddr (virtPage) + offset
while offset < PAGE_SIZE
* (destAddr asPtrTo char) = * (kernelAddr asPtrTo char)
offset = offset + 1
kernelAddr = kernelAddr + 1
destAddr = destAddr + 1
copiedSoFar = copiedSoFar + 1
if copiedSoFar == numBytes
return copiedSoFar
endIf
endWhile
virtPage = virtPage + 1
offset = 0
endWhile
endMethod
---------- AddrSpace . GetStringFromVirtual ----------
method GetStringFromVirtual (kernelAddr: String, virtAddr, maxSize: int) returns int
--
-- This method is used to copy a String from virtual space into
-- a given physical address in the kernel. The "kernelAddr" should be
-- a pointer to an "array of char" in the kernel's code. This method
-- copies up to "maxSize" characters from approriate page frame to this
-- to the target array in the kernel.'
--
-- Note: This method resets the "arraySize" word in the target. It is
-- assumed that the target array has enough space; no checking is done.
-- The caller should supply a "maxSize" telling how many characters may
-- be safely copied.
--
-- If there are problems, then -1 is returned. Possible problems:
-- The source array has more than "maxSize" elements
-- The source page is invalid or out of range
-- If all okay, then the number of characters copied is returned.
--
var sourceSize: int
-- print ("GetStringFromVirtual called...\n")
-- printHexVar (" kernelAddr", kernelAddr asInteger)
-- printHexVar (" virtAddr", virtAddr)
-- printIntVar (" maxSize", maxSize)
-- Begin by fetching the source size
if self.CopyBytesFromVirtual ((&sourceSize) asInteger,
virtAddr,
4) < 4
return -1
endIf
-- printIntVar (" sourceSize", sourceSize)
-- Make sure the source size is okay
if sourceSize > maxSize
return -1
endIf
-- Change the size of the destination array
* (kernelAddr asPtrTo int) = sourceSize
-- Next, get the characters
return self.CopyBytesFromVirtual (kernelAddr asInteger + 4,
virtAddr + 4,
sourceSize)
endMethod
endBehavior
----------------------------- TimerInterruptHandler ---------------------------------
function TimerInterruptHandler ()
--
-- This routine is called when a timer interrupt occurs. Upon entry,
-- interrupts are DISABLED. Upon return, execution will return to
-- the interrupted process, which necessarily had interrupts ENABLED.
--
-- (If you wish to turn time-slicing off, simply disable the call
-- to "Yield" in the code below. Threads will then execute until they
-- call "Yield" explicitly, or until they call "Sleep".)
--
currentInterruptStatus = DISABLED
-- printChar ('_')
currentThread.Yield ()
currentInterruptStatus = ENABLED
endFunction
----------------------------- DiskInterruptHandler --------------------------
function DiskInterruptHandler ()
--
-- This routine is called when a disk interrupt occurs. It will
-- signal the "semToSignalOnCompletion" Semaphore and return to
-- the interrupted thread.
--
-- This is an interrupt handler. As such, interrupts will be DISABLED
-- for the duration of its execution.
--
-- Uncomment this code later...
--FatalError ("DISK INTERRUPTS NOT EXPECTED IN PROJECT 4")
currentInterruptStatus = DISABLED
-- print ("DiskInterruptHandler invoked!\n")
if diskDriver.semToSignalOnCompletion
diskDriver.semToSignalOnCompletion.Up()
endIf
endFunction
----------------------------- SerialInterruptHandler --------------------------
function SerialInterruptHandler ()
--
-- This routine is called when a serial interrupt occurs. It will
-- signal the "semToSignalOnCompletion" Semaphore and return to
-- the interrupted thread.
--
-- This is an interrupt handler. As such, interrupts will be DISABLED
-- for the duration of its execution.
--
currentInterruptStatus = DISABLED
-- NOT IMPLEMENTED
endFunction
----------------------------- IllegalInstructionHandler --------------------------
function IllegalInstructionHandler ()
--
-- This routine is called when an IllegalInstruction exception occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An IllegalInstruction exception has occured while in user mode")
endFunction
----------------------------- ArithmeticExceptionHandler --------------------------
function ArithmeticExceptionHandler ()
--
-- This routine is called when an ArithmeticException occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An ArithmeticException exception has occured while in user mode")
endFunction
----------------------------- AddressExceptionHandler --------------------------
function AddressExceptionHandler ()
--
-- This routine is called when an AddressException occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An AddressException exception has occured while in user mode")
endFunction
----------------------------- PageInvalidExceptionHandler --------------------------
function PageInvalidExceptionHandler ()
--
-- This routine is called when a PageInvalidException occurs. Upon entry,
-- interrupts are DISABLED. For now, we simply print a message and abort
-- the thread.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("A PageInvalidException exception has occured while in user mode")
endFunction
----------------------------- PageReadonlyExceptionHandler --------------------------
function PageReadonlyExceptionHandler ()
--
-- This routine is called when a PageReadonlyException occurs. Upon entry,
-- interrupts are DISABLED. For now, we simply print a message and abort
-- the thread.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("A PageReadonlyException exception has occured while in user mode")
endFunction
----------------------------- PrivilegedInstructionHandler --------------------------
function PrivilegedInstructionHandler ()
--
-- This routine is called when a PrivilegedInstruction exception occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("A PrivilegedInstruction exception has occured while in user mode")
endFunction
----------------------------- AlignmentExceptionHandler --------------------------
function AlignmentExceptionHandler ()
--
-- This routine is called when an AlignmentException occurs. Upon entry,
-- interrupts are DISABLED. We should not return to the code that had
-- the exception.
--
currentInterruptStatus = DISABLED
ErrorInUserProcess ("An AlignmentException exception has occured while in user mode")
endFunction
----------------------------- ErrorInUserProcess --------------------------
function ErrorInUserProcess (errorMessage: String)
--
-- This routine is called when an error has occurred in a user-level
-- process. It prints the error message and terminates the process.
--
print ("\n********** ")
print (errorMessage)
print (" **********\n\n")
-- Print some information about the offending process...
if currentThread.myProcess
currentThread.myProcess.Print ()
else
print (" ERROR: currentThread.myProcess is null\n\n")
endIf
currentThread.Print ()
-- Uncomment the following for even more information...
-- threadManager.Print ()
-- processManager.Print ()
ProcessFinish (-1)
endFunction
----------------------------- SyscallTrapHandler --------------------------
function SyscallTrapHandler (syscallCodeNum, arg1, arg2, arg3, arg4: int) returns int
--
-- This routine is called when a syscall trap occurs. Upon entry, interrupts
-- will be DISABLED, paging is disabled, and we will be running in System mode.
-- Upon return, execution will return to the user mode portion of this
-- thread, which will have had interrupts ENABLED.
--
currentInterruptStatus = DISABLED
/*****
print ("Within SyscallTrapHandler: syscallCodeNum=")
printInt (syscallCodeNum)
print (", arg1=")
printInt (arg1)
print (", arg2=")
printInt (arg2)
print (", arg3=")
printInt (arg3)
print (", arg4=")
printInt (arg4)
nl ()
*****/
switch syscallCodeNum
case SYSCALL_FORK:
return Handle_Sys_Fork ()
case SYSCALL_YIELD:
Handle_Sys_Yield ()
return 0
case SYSCALL_EXEC:
return Handle_Sys_Exec (arg1 asPtrTo array of char)
case SYSCALL_JOIN:
return Handle_Sys_Join (arg1)
case SYSCALL_EXIT:
Handle_Sys_Exit (arg1)
return 0
case SYSCALL_CREATE:
return Handle_Sys_Create (arg1 asPtrTo array of char)
case SYSCALL_OPEN:
return Handle_Sys_Open (arg1 asPtrTo array of char)
case SYSCALL_READ:
return Handle_Sys_Read (arg1, arg2 asPtrTo char, arg3)
case SYSCALL_WRITE:
return Handle_Sys_Write (arg1, arg2 asPtrTo char, arg3)
case SYSCALL_SEEK:
return Handle_Sys_Seek (arg1, arg2)
case SYSCALL_CLOSE:
Handle_Sys_Close (arg1)
return 0
case SYSCALL_SHUTDOWN:
Handle_Sys_Shutdown ()
return 0
default:
print ("Syscall code = ")
printInt (syscallCodeNum)
nl ()
FatalError ("Unknown syscall code from user thread")
endSwitch
return 0
endFunction
----------------------------- Handle_Sys_Exit ---------------------------------
-- Modify all the syscall handlers so they print the arguments that are passed to them.
function Handle_Sys_Exit (returnStatus: int)
-- IMPLEMENTED
print("Handle_Sys_Exit invoked! \n")
print("returnStatus = ")
printInt(returnStatus)
print("\n")
endFunction
----------------------------- Handle_Sys_Shutdown ---------------------------------
function Handle_Sys_Shutdown ()
-- IMPLEMENTED
-- handler should call FatalError
-- This function will cause an immediate shutdown of the kernel. It will not return.
FatalError("Syscall 'Shutdown' was invoked by a user thread")
endFunction
----------------------------- Handle_Sys_Yield ---------------------------------
function Handle_Sys_Yield ()
-- IMPLEMENTED
print("Handle_Sys_Yield invoked! \n")
endFunction
----------------------------- Handle_Sys_Fork ---------------------------------
function Handle_Sys_Fork () returns int
-- IMPLEMENTED
print("Handle_Sys_Fork invoked! \n")
return 1000
endFunction
----------------------------- Handle_Sys_Join ---------------------------------
function Handle_Sys_Join (processID: int) returns int
-- IMPLEMENTED
print("Handle_Sys_Join invoked! \n")
print("processID = ")
printInt(processID)
print("\n")
return 2000
endFunction
----------------------------- Handle_Sys_Exec ---------------------------------
function Handle_Sys_Exec (filename: ptr to array of char) returns int
-- IMPLEMENTED
-- The sequence of steps in InitFirstProcess and StartUserProcess is very similar to what
-- you’ll need when implementing the Exec syscall.
-- One difference is that during an Exec, you already have a process and a thread, so you will not need to
-- allocate a new ProcesControlBlock, allocate a new Thread object, or do a fork. However, you will
-- have to work with two virtual address spaces. The LoadExecutable method requires an empty
-- AddrSpace object; it will then allocate as many frames as necessary and initialize the new address
-- space.
var
fileptr: ptr to OpenFile
initPC: int -- get initial address of program counter
initUserStackTop: int
initSystemStackTop: ptr to int
oldinterrupt: int
-- Don’t allocate it on the heap
newAddrSpace: AddrSpace
-- we do not want to allocate anything on the heap after kernel start-up.
strBuffer: array [MAX_STRING_SIZE] of char
i: int
newAddrSpace = new AddrSpace
newAddrSpace.Init()
-- copying the filename string from a virtual address space into the kernel address
-- space where it can be used. The filename argument is a virtual address, but since the kernel is running
-- in Handle_Sys_Exec, paging will be turned off.
-- copy the characters into an array variable.
-- put a maximum size on this array and then check that it is not exceeded
-- the filename pointer is virtual address, which must be translated into a physical address.
-- the filename string is in virtual space, it may cross page boundaries.
-- Use method GetStringFromVirtual (kernelAddr: String, virtAddr, maxSize: int) returns int
i = currentThread.myProcess.addrSpace.GetStringFromVirtual (& strBuffer, filename asInteger, MAX_STRING_SIZE)
if i < 0
-- FatalError("Error: copying the filename string from a virtual address space into the kernel address failed")
return -1
endIf
-- open the executable file.
fileptr = fileManager.Open(& strBuffer)
if fileptr == null
-- FatalError("Error: the executable file kernel startup process failed")
return -1
endIf
-- create the logical address space and read the executable into it.
-- LoadExecutable may fail and, if so, your kernel must be able to return to the process
-- that invoked Exec (with an error code, of course). So you better not get rid of the old address space
-- until after the new one has been initialized and you can be sure that no more errors can occur.
initPC = fileptr.LoadExecutable(&newAddrSpace)
if initPC == -1
-- FatalError("Error: the executable file kernel startup process failed")
return -1
endIf
-- Don’t forget to close the executable file you opened earlier
fileManager.Close(fileptr)
-- Don’t forget to free the frames in the previous address space first, or else valuable kernel resources will
-- remain forever unavailable and the kernel will eventually freeze up!
frameManager.ReturnAllFrames(¤tThread.myProcess.addrSpace)
-- after the new address space has been set up, you can copy it into the ProcessControlBlock
currentThread.myProcess.addrSpace = newAddrSpace
-- compute the initial value for the user-level stack,
initUserStackTop = newAddrSpace.numberOfPages * PAGE_SIZE
-- a full-sized system stack available for processing any syscalls or interrupts
-- that happen later
initSystemStackTop = & currentThread.systemStack[SYSTEM_STACK_SIZE-1]
-- turn this thread into a user-level thread
-- 1. Disable interrupts (every thread begins life with interrupts enabled)
oldinterrupt = SetInterruptsTo(DISABLED)
-- 2. Initialize the page table registers for this logical address space
newAddrSpace.SetToThisPageTable()
-- 3. Set the isUserThread variable in the current thread to true
currentThread.isUserThread = true
-- steps (4) through (9) must be done in assembly language
-- The BecomeUserThread will change the mode bits and perform the jump “atomically.”
-- BecomeUserThread jumps to the user-level main routine and never returns.
BecomeUserThread(initUserStackTop, initPC, initSystemStackTop asInteger)
-- syscalls return a result
return 3000
endFunction
----------------------------- Handle_Sys_Create ---------------------------------
function Handle_Sys_Create (filename: ptr to array of char) returns int
-- IMPLEMENTED
-- This pointer is in the user-program’s logical address space. You must first move the string from userspace
-- to a buffer in kernel space. Only then can it be safely printed.
var
strBuffer: array [MAX_STRING_SIZE] of char
i: int
i = currentThread.myProcess.addrSpace.GetStringFromVirtual (& strBuffer, filename asInteger, MAX_STRING_SIZE)
if i < 0
FatalError("Error: copying the filename string from a virtual address space into the kernel address failed")
endIf
print("Handle_Sys_Create invoked! \n")
print("virt addr of filename = ")
printHex(filename asInteger)
print("\n")
print("filename = ")
print(&strBuffer)
print("\n")
return 4000
endFunction
----------------------------- Handle_Sys_Open ---------------------------------
function Handle_Sys_Open (filename: ptr to array of char) returns int
-- IMPLEMENTED
var
strBuffer: array [MAX_STRING_SIZE] of char
i: int
i = currentThread.myProcess.addrSpace.GetStringFromVirtual (& strBuffer, filename asInteger, MAX_STRING_SIZE)
if i < 0
FatalError("Error: copying the filename string from a virtual address space into the kernel address failed")
endIf
print("Handle_Sys_Open invoked! \n")
print("virt addr of filename = ")
printHex(filename asInteger)
print("\n")
print("filename = ")
print(&strBuffer)
print("\n")
return 5000
endFunction
----------------------------- Handle_Sys_Read ---------------------------------
function Handle_Sys_Read (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int
-- IMPLEMENTED
print("Handle_Sys_Read invoked! \n")
print("fileDesc = ")
printInt(fileDesc)
print("\n")
print("virt addr of buffer = ")
printHex(buffer asInteger)
print("\n")
print("sizeInBytes = ")
printInt(sizeInBytes)
print("\n")
return 6000
endFunction
----------------------------- Handle_Sys_Write ---------------------------------
function Handle_Sys_Write (fileDesc: int, buffer: ptr to char, sizeInBytes: int) returns int
-- IMPLEMENTED
print("Handle_Sys_Write invoked! \n")
print("fileDesc = ")
printInt(fileDesc)
print("\n")
print("virt addr of buffer = ")
printHex(buffer asInteger)
print("\n")
print("sizeInBytes = ")
printInt(sizeInBytes)
print("\n")
return 7000
endFunction
----------------------------- Handle_Sys_Seek ---------------------------------
function Handle_Sys_Seek (fileDesc: int, newCurrentPos: int) returns int
-- IMPLEMENTED
print("Handle_Sys_Seek invoked! \n")
print("fileDesc = ")
printInt(fileDesc)
print("\n")
print("newCurrentPos = ")
printInt(newCurrentPos)
print("\n")
return 8000
endFunction
----------------------------- Handle_Sys_Close ---------------------------------
function Handle_Sys_Close (fileDesc: int)
-- IMPLEMENTED
print("Handle_Sys_Close invoked! \n")
print("fileDesc = ")
printInt(fileDesc)
print("\n")
endFunction
----------------------------- InitFirstProcess ---------------------------------
-- Creating a User-Level Process
function InitFirstProcess ()
var
processthreadptr: ptr to Thread
-- get a new thread object by invoking GetANewThread. Since the InitFirstProcess
-- function should return, cannot use the current thread.
processthreadptr = threadManager.GetANewThread()
-- name this new thread something like “UserProgram,” but the
-- name is only used in the debugging printouts.
processthreadptr.name = "UserProgram"
-- initialize the thread and invoke Fork to start it running.
-- The new thread should execute the StartUserProcess function
-- InitFirstProcess can supply a zero as an argument to
-- StartUserProcess and can return after forking the new thread
processthreadptr.Fork(StartUserProcess, 0)
endFunction
function StartUserProcess ()
-- starting up a user-level process
-- The StartUserProcess function will end by jumping into the user-level program.
-- This is a one way jump; execution will never return. (Instead, if the user-level
-- program needs to re-enter the kernel, it will execute a syscall). As such,
-- nothing on the system stack will ever be needed again.
var
pcbptr: ptr to ProcessControlBlock
fileptr: ptr to OpenFile
initPC: int -- get initial address of program counter
initUserStackTop: int
initSystemStackTop: ptr to int
oldinterrupt: int
-- allocate a new ProcessControlBlock (with GetANewProcess) and connect it with the thread.
-- So initialize the myThread field in the PCB and the myProcess field in
-- the current thread.
pcbptr = processManager.GetANewProcess()
-- the first process thread
pcbptr.myThread = currentThread
-- the first thread process
currentThread.myProcess = pcbptr
-- open the executable file. It is acceptable to “hardcode” the filename (e.g.,
-- “TestProgram1”) into the call to Open
-- changing the name of the initial process will require a recompile of the kernel.
-- If there are problems with the Open, this is a fatal, unrecoverable error and the
-- kernel startup process will fail.
fileptr = fileManager.Open("TestProgram1")
if fileptr == null
FatalError("Error: the executable file kernel startup process failed")
endIf
-- create the logical address space and read the executable into it.
-- The method OpenFile.LoadExecutable will take care of both tasks.
-- If this fails, the kernel cannot start up.
-- LoadExecutable returns the entry point, which you might call initPC
initPC = fileptr.LoadExecutable(&pcbptr.addrSpace)
if initPC == -1
FatalError("Error: the executable file kernel startup process failed")
endIf
-- Don’t forget to close the executable file you opened earlier, or else a system
-- resource will be permanently locked up.
fileManager.Close(fileptr)
-- compute the initial value for the user-level stack, which you might call
-- initUserStackTop. It should be set to the logical address just past the end
-- of the logical address space, since the initial push onto the user stack will
-- first decrement the top pointer.
-- The logical address space starts at zero. The logical address space contains
-- addrSpace.numberOfPages pages. Each page has size PAGE_SIZE bytes
initUserStackTop = pcbptr.addrSpace.numberOfPages * PAGE_SIZE
-- a full-sized system stack available for processing any syscalls or interrupts
-- that happen later, to reset the system stack top pointer, effectively clearing
-- the system stack.
initSystemStackTop = & currentThread.systemStack[SYSTEM_STACK_SIZE-1]
-- turn this thread into a user-level thread
-- 1. Disable interrupts (every thread begins life with interrupts enabled)
oldinterrupt = SetInterruptsTo(DISABLED)
-- possible race conditions with steps (2) and (3)
-- if a context switch (i.e., timer interrupt) were to occur between setting the
-- page table registers and setting isUserThread to true.
-- The MMU registers would be changed for the other process; then when this thread
-- is once again scheduled, the code in Run will see isUserThread==false so it will
-- not restore the MMU registers. Merely swapping the order of steps (2) and (3)
-- results in a similar race condition
-- 2. Initialize the page table registers for this logical address space
pcbptr.addrSpace.SetToThisPageTable()
-- 3. Set the isUserThread variable in the current thread to true
currentThread.isUserThread = true
-- steps (4) through (9) must be done in assembly language
-- 4. Set system register r15, the system stack top
-- 5. Set user register r15, the user stack top
-- 6. Clear the System mode bit in the condition code register to switch into user mode
-- 7. Set the Paging bit in the cond. code register, causing the MMU to do virtual memory mapping
-- 8. Set the Interrupts Enabled bit in the cond. code register, so that future interrupts will be handled
-- 9. Jump to the initial entry point in the program
-- From assembly routine in the file Switch.s: BecomeUserThread (initStack, initPC, initSystemStack: int)
-- The BecomeUserThread will change the mode bits and perform the jump “atomically.”
-- This must be done atomically since the target jump address is a logical address space.
-- BecomeUserThread jumps to the user-level main routine and never returns.
BecomeUserThread(initUserStackTop, initPC, initSystemStackTop asInteger)
endFunction
----------------------------- DiskDriver ---------------------------------
const
DISK_STATUS_BUSY = 0x00000000
DISK_STATUS_OPERATION_COMPLETED_OK = 0x00000001
DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_1 = 0x00000002
DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_2 = 0x00000003
DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_3 = 0x00000004
DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_4 = 0x00000005
DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_5 = 0x00000006
DISK_READ_COMMAND = 0x00000001
DISK_WRITE_COMMAND = 0x00000002
behavior DiskDriver
--
-- There is only one instance of this class. It provides "read" and "write"
-- methods to transfer data from and to the disk.
--
-- In this implementation, all I/O is synchronous. These methods perform
-- busy-waiting until the disk operation has completed.
---------- DiskDriver . Init ----------
method Init ()
print ("Initializing Disk Driver...\n")
DISK_STATUS_WORD_ADDRESS = 0x00FFFF08 asPtrTo int
DISK_COMMAND_WORD_ADDRESS = 0x00FFFF08 asPtrTo int
DISK_MEMORY_ADDRESS_REGISTER = 0x00FFFF0C asPtrTo int
DISK_SECTOR_NUMBER_REGISTER = 0x00FFFF10 asPtrTo int
DISK_SECTOR_COUNT_REGISTER = 0x00FFFF14 asPtrTo int
semToSignalOnCompletion = null
semUsedInSynchMethods = new Semaphore
semUsedInSynchMethods.Init (0)
diskBusy = new Mutex
diskBusy.Init ()
endMethod
---------- DiskDriver . SynchReadSector ----------
method SynchReadSector (sectorAddr, numberOfSectors, memoryAddr: int)
--
-- This method reads "numberOfSectors" sectors (of PAGE_SIZE bytes each)
-- from the disk and places the data in memory, starting at "memoryAddr".
-- It waits until the I/O is complete before returning.
--
-- If there is a (simulated) disk hardware failure, then this routine
-- simply tries again in an infinite loop, until it succeeds.
--
-- print ("SynchReadSector called\n")
-- printIntVar (" sectorAddr", sectorAddr)
-- printIntVar (" numberOfSectors", numberOfSectors)
-- printHexVar (" memoryAddr", memoryAddr)
diskBusy.Lock ()
while true
self.StartReadSector (sectorAddr, numberOfSectors, memoryAddr,
& semUsedInSynchMethods)
semUsedInSynchMethods.Down ()
-- Check the return status
switch * DISK_STATUS_WORD_ADDRESS
case DISK_STATUS_OPERATION_COMPLETED_OK:
diskBusy.Unlock ()
return
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_1:
FatalError ("Disk I/O error in SynchReadSector: Memory addr is not page-aligned or sector count is not positive")
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_2:
FatalError ("Disk I/O error in SynchReadSector: Attempt to access invalid memory address")
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_3:
FatalError ("Disk I/O error in SynchReadSector: Bad sectorAddr or sectorCount specifies non-existant sector")
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_4:
-- This case occurs when there is a hard or soft (simulated)
-- hardware error while performing the disk operation.
break
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_5:
FatalError ("Disk I/O error in SynchReadSector: Bad command word")
default:
FatalError ("SynchReadSector: Unexpected status code")
endSwitch
-- print ("\n\nIn SynchReadSector: A simulated disk I/O error occurred...\n\n")
endWhile
endMethod
---------- DiskDriver . StartReadSector ----------
method StartReadSector (sectorAddr, numberOfSectors, memoryAddr: int,
whoCares: ptr to Semaphore)
--
-- This method reads "numberOfSectors" sectors (of PAGE_SIZE bytes each)
-- from the disk and places the data in memory, starting at "memoryAddr".
-- The "whoCares" argument is a Semaphore that we will signal after the
-- I/O operation is complete; if null no thread will be notified.
--
-- print ("StartReadSector called\n")
-- printIntVar (" sectorAddr", sectorAddr)
-- printIntVar (" numberOfSectors", numberOfSectors)
-- printHexVar (" memoryAddr", memoryAddr)
-- printHexVar (" whoCares", whoCares asInteger)
-- Save the semaphore
semToSignalOnCompletion = whoCares
-- Move the parameters to the disk and start the I/O
* DISK_MEMORY_ADDRESS_REGISTER = memoryAddr
* DISK_SECTOR_NUMBER_REGISTER = sectorAddr
* DISK_SECTOR_COUNT_REGISTER = numberOfSectors
* DISK_COMMAND_WORD_ADDRESS = DISK_READ_COMMAND -- Starts the I/O
endMethod
---------- DiskDriver . SynchWriteSector ----------
method SynchWriteSector (sectorAddr, numberOfSectors, memoryAddr: int)
--
-- This method writes "numberOfSectors" sectors (of PAGE_SIZE bytes each)
-- to the disk. It waits until the I/O is complete before returning.
--
-- If there is a (simulated) disk hardware failure, then this routine
-- simply tries again in an infinite loop, until it succeeds.
--
-- print ("SynchWriteSector called\n")
-- printIntVar (" sectorAddr", sectorAddr)
-- printIntVar (" numberOfSectors", numberOfSectors)
-- printHexVar (" memoryAddr", memoryAddr)
diskBusy.Lock ()
while true
self.StartWriteSector (sectorAddr, numberOfSectors, memoryAddr,
& semUsedInSynchMethods)
semUsedInSynchMethods.Down ()
-- Check the return status
switch * DISK_STATUS_WORD_ADDRESS
case DISK_STATUS_OPERATION_COMPLETED_OK:
diskBusy.Unlock ()
return
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_1:
FatalError ("Disk I/O error in SynchWriteSector: Memory addr is not page-aligned or sector count is not positive")
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_2:
FatalError ("Disk I/O error in SynchWriteSector: Attempt to access invalid memory address")
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_3:
FatalError ("Disk I/O error in SynchWriteSector: Bad sectorAddr or sectorCount specifies non-existant sector")
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_4:
-- This case occurs when there is a hard or soft (simulated)
-- hardware error while performing the disk operation.
break
case DISK_STATUS_OPERATION_COMPLETED_WITH_ERROR_5:
FatalError ("Disk I/O error in SynchWriteSector: Bad command word")
default:
FatalError ("SynchWriteSector: Unexpected status code")
endSwitch
-- print ("\n\nIn SynchWriteSector: A simulated disk I/O error occurred...\n\n")
endWhile
endMethod
---------- DiskDriver . StartWriteSector ----------
method StartWriteSector (sectorAddr, numberOfSectors, memoryAddr: int,
whoCares: ptr to Semaphore)
--
-- This method writes "numberOfSectors" sectors (of PAGE_SIZE bytes each)
-- to the disk. It returns immediately after starting the I/O.
--
-- The "whoCares" argument is a Semaphore that we will signal after the
-- I/O operation is complete; if null no thread will be notified.
--
-- print ("SynchWriteSector called\n")
-- printIntVar (" sectorAddr", sectorAddr)
-- printIntVar (" numberOfSectors", numberOfSectors)
-- printHexVar (" memoryAddr", memoryAddr)
-- Save the semaphore
semToSignalOnCompletion = whoCares
* DISK_MEMORY_ADDRESS_REGISTER = memoryAddr
* DISK_SECTOR_NUMBER_REGISTER = sectorAddr
* DISK_SECTOR_COUNT_REGISTER = numberOfSectors
* DISK_COMMAND_WORD_ADDRESS = DISK_WRITE_COMMAND -- Starts the I/O
endMethod
endBehavior
----------------------------- FileManager ---------------------------------
behavior FileManager
---------- FileManager . Init ----------
method Init ()
--
-- This method is called once at kernel startup time to initialize
-- the one and only "FileManager" object. It is passed a pointer
-- to a frame of memory.
--
var i: int
print ("Initializing File Manager...\n")
fileManagerLock = new Mutex
fileManagerLock.Init ()
-- Initialize the FileControlBlock stuff
fcbFreeList = new List [FileControlBlock]
anFCBBecameFree = new Condition
anFCBBecameFree.Init ()
fcbTable = new array of FileControlBlock
{ MAX_NUMBER_OF_FILE_CONTROL_BLOCKS of new FileControlBlock }
for i = 0 to MAX_NUMBER_OF_FILE_CONTROL_BLOCKS-1
fcbTable[i].fcbID = i
fcbTable[i].Init()
fcbFreeList.AddToEnd (&fcbTable[i])
endFor
-- Initialize the OpenFile stuff
openFileFreeList = new List [OpenFile]
anOpenFileBecameFree = new Condition
anOpenFileBecameFree.Init ()
openFileTable = new array of OpenFile
{ MAX_NUMBER_OF_OPEN_FILES of new OpenFile }
for i = 0 to MAX_NUMBER_OF_OPEN_FILES-1
openFileTable[i].kind = FILE
openFileFreeList.AddToEnd (&openFileTable[i])
endFor
-- Create the special "stdin/stdout" open file
serialTerminalFile = new OpenFile
serialTerminalFile.kind = TERMINAL
-- Read in sector 0 from the disk. This is the
-- "Stub System" directory page. We'll just keep this around'
-- forever, for use whenever we want to open a file.
directoryFrame = frameManager.GetAFrame ()
diskDriver.SynchReadSector (0, -- sector to read
1, -- number of sectors to read
directoryFrame)
endMethod
---------- FileManager . Print ----------
method Print ()
var i: int
fileManagerLock.Lock () -- Need lock since we touch freeLists
print ("Here is the FileControlBlock table...\n")
for i = 0 to MAX_NUMBER_OF_FILE_CONTROL_BLOCKS-1
print (" ")
printInt (i)
print (": ")
fcbTable[i].Print()
endFor
print ("Here is the FREE list of FileControlBlocks:\n ")
fcbFreeList.ApplyToEach (printFCB)
nl ()
print ("Here is the OpenFile table...\n")
for i = 0 to MAX_NUMBER_OF_OPEN_FILES-1
print (" ")
printInt (i)
print (": 0x")
printHex ((& openFileTable[i]) asInteger)
print (": ")
openFileTable[i].Print()
endFor
print ("Here is the FREE list of OpenFiles:\n")
openFileFreeList.ApplyToEach (printOpen)
fileManagerLock.Unlock ()
endMethod
---------- FileManager . Open ----------
method Open (filename: String) returns ptr to OpenFile
--
-- This method is called to open a file. It returns pointer to
-- a newly allocated OpenFile. It will set its "numberOfUsers"
-- count to 1.
--
-- The file must already exist on the disk. If it cannot be found,
-- this method returns null.
--
-- This method is reentrant, and may block the caller.
--
var open: ptr to OpenFile
fcb: ptr to FileControlBlock
-- First, get an FCB that points to the file.
-- This will increment fcb.numberOfUsers.
fcb = fileManager.FindFCB (filename)
if fcb == null
return null
endIf
-- Next, allocate an OpenFile, waiting if necessary.
fileManagerLock.Lock()
while openFileFreeList.IsEmpty ()
anOpenFileBecameFree.Wait (& fileManagerLock)
endWhile
open = openFileFreeList.Remove ()
-- Connect it to this FCB and set its "numberOfUsers" count.
open.fcb = fcb
open.numberOfUsers = 1
-- printHexVar ("open.fcb", open.fcb asInteger)
open.currentPos = 0
-- Release FileManagerLock and return a pointer to the OpenFile object
fileManagerLock.Unlock()
return open
endMethod
---------- FileManager . FindFCB ----------
method FindFCB (filename: String) returns ptr to FileControlBlock
--
-- This method is called when opening a file. The file may already be
-- open; if so we return a pointer to the FCB that describes that
-- file. If not, we allocate a new FCB and return a pointer to it.
--
-- The file must already exist on the disk. If it cannot be found,
-- this method returns null.
--
-- The numberOfUsers field in the FCB is incremented.
--
-- This implementation is a "dummy" implementation, using the "stub"
-- file system. The stub file system has a single directory which
-- is stored in sector 0. When the fileManager was initialized, sector
-- 0 was pre-read, so all we do here is consult it to locate the
-- the file. Then we store the relevant info in the FCB.
--
-- This method is reentrant, and may block the caller.
--
var i, start, numFiles, fileLen, fileNameLen: int
fcb: ptr to FileControlBlock
p: ptr to int
-- print ("Opening a file\n")
-- Begin the search with byte 0 of the directory sector
p = directoryFrame asPtrTo int
-- Check the magic number
i = *p
p = p + 4
if i != 0x73747562 -- in ASCII this is "stub"
FatalError ("Magic number in sector 0 of stub file system is bad")
endIf
-- Get the number of files in the directory
numFiles = *p
p = p + 4
i = *p -- This is the nextFreeSector; ignore it.
p = p + 4
-- Run through each directory entry, looking for a match
while numFiles > 0
copyUnalignedWord (&start, p)
p = p + 4
copyUnalignedWord (&fileLen, p)
p = p + 4
copyUnalignedWord (&fileNameLen, p)
p = p + 4
if fileNameLen == filename arraySize &&
MemoryEqual (p asPtrTo char, &filename[0], fileNameLen)
break
endIf
p = p + fileNameLen
numFiles = numFiles - 1
endWhile
-- If we didn't find a matching name, return null'
if numFiles <= 0
return null
endIf
fileManagerLock.Lock()
-- See if there is an FCB for this file; if so return it.
for i = 0 to MAX_NUMBER_OF_FILE_CONTROL_BLOCKS-1
fcb = &fcbTable[i]
if fcb.startingSectorOfFile == start
fcb.numberOfUsers = fcb.numberOfUsers + 1
fileManagerLock.Unlock()
return fcb
endIf
endFor
-- Get an unused FCB, waiting until one becomes available
while fcbFreeList.IsEmpty ()
anFCBBecameFree.Wait (& fileManagerLock)
endWhile
fcb = fcbFreeList.Remove ()
-- Safe to unlock now, since no one else will use this FCB
fileManagerLock.Unlock()
-- Set the FCB up, and return it.
fcb.startingSectorOfFile = start
fcb.sizeOfFileInBytes = fileLen
fcb.numberOfUsers = 1
if fcb.relativeSectorInBuffer >= 0 || fcb.bufferIsDirty
FatalError ("In FileManager.Open: a free FCB appears not to have been closed properly")
endIf
return fcb
endMethod
---------- FileManager . Close ----------
--
-- This method is called to close an OpenFile. If there is a pending
-- write (i.e., the buffer is dirty) then it is written out first.
--
-- The "numberOfUsers" for the OpenFile is decremented and, if zero,
-- the OpenFile is freed. If the OpenFile is freed, then the
-- "numberOfUsers" for the FCB is decremented. If it too is zero, the
-- FCB is freed.
--
method Close (open: ptr to OpenFile)
var fcb: ptr to FileControlBlock
if open == & serialTerminalFile
return
endIf
fileManagerLock.Lock()
fileManager.Flush (open)
fcb = open.fcb
open.numberOfUsers = open.numberOfUsers - 1
if open.numberOfUsers <= 0
openFileFreeList.AddToEnd (open)
anOpenFileBecameFree.Signal (& fileManagerLock)
fcb.numberOfUsers = fcb.numberOfUsers - 1
if fcb.numberOfUsers <= 0
fcbFreeList.AddToEnd (fcb)
anFCBBecameFree.Signal (& fileManagerLock)
endIf
endIf
fileManagerLock.Unlock()
endMethod
---------- FileManager . Flush ----------
method Flush (open: ptr to OpenFile)
--
-- This method writes out the buffer, if it is dirty. This method
-- assumes the caller already holds the fileManagerLock.
--
if open.fcb.bufferIsDirty
if open.fcb.relativeSectorInBuffer < 0
FatalError ("FileManager.Flush: buffer is dirty but relativeSectorInBuffer = -1")
endIf
open.fcb.bufferIsDirty = false
diskDriver.SynchWriteSector (
open.fcb.relativeSectorInBuffer+open.fcb.startingSectorOfFile,
1,
open.fcb.bufferPtr)
endIf
endMethod
---------- FileManager . SynchRead ----------
method SynchRead (open: ptr to OpenFile,
targetAddr, bytePos, numBytes: int) returns bool
--
-- This method reads "numBytes" from this file and stores
-- them at the address pointed to by "targetAddr". If everything
-- was read okay, it returns TRUE; if problems it returns FALSE.
--
-- It reads a page at a time into an internal buffer
-- by calling "diskDriver.SynchReadSector".
--
var sector, offset, posInBuffer, bytesToMove: int
fcb: ptr to FileControlBlock
-- printHexVar ("SynchRead called targetAddr", targetAddr)
-- printIntVar (" bytePos", bytePos)
-- printIntVar (" numBytes", numBytes)
fileManagerLock.Lock()
if ! open || ! open.fcb || open.fcb.startingSectorOfFile < 0
FatalError ("FileManager.SynchRead: file not properly opened")
endIf
fcb = open.fcb
while numBytes > 0
-- At this point targetAddr and numBytes tell what work is left to do.
-- printHexVar ("NEXT MOVE:\n targetAddr", targetAddr)
-- printIntVar (" numBytes", numBytes)
-- printHexVar (" ", numBytes)
-- printIntVar (" startingSectorOfFile", fcb.startingSectorOfFile)
-- printIntVar (" relativeSectorInBuffer", fcb.relativeSectorInBuffer)
-- printIntVar (" bytePos", bytePos)
-- printHexVar (" ", bytePos)
sector = bytePos / PAGE_SIZE
offset = bytePos % PAGE_SIZE
-- printIntVar (" sector", sector)
-- printIntVar (" offset", offset)
-- printHexVar (" ", offset)
if fcb.relativeSectorInBuffer != sector
self.Flush (open)
-- printIntVar (" READING SECTOR", sector+startingSectorOfFile)
diskDriver.SynchReadSector (sector + fcb.startingSectorOfFile,
1,
fcb.bufferPtr)
fcb.relativeSectorInBuffer = sector
fcb.bufferIsDirty = false -- (This is unnecessary since Flush does it)
endIf
posInBuffer = fcb.bufferPtr + offset
bytesToMove = Min (numBytes, PAGE_SIZE - offset)
-- printHexVar (" MOVING - targetAddr", targetAddr)
-- printHexVar (" - source addr (posInBuffer)", posInBuffer)
-- printIntVar (" - bytesToMove", bytesToMove)
MemoryCopy (targetAddr, posInBuffer, bytesToMove)
targetAddr = targetAddr + bytesToMove
bytePos = bytePos + bytesToMove
numBytes = numBytes - bytesToMove
-- printHexVar (" NEW targetAddr", targetAddr)
-- printIntVar (" NEW bytePos", bytePos)
-- printHexVar (" ", bytePos)
-- printIntVar (" NEW numBytes", numBytes)
-- printHexVar (" ", numBytes)
endWhile
fileManagerLock.Unlock()
return true
endMethod
---------- FileManager . SynchWrite ----------
method SynchWrite (open: ptr to OpenFile,
sourceAddr, bytePos, numBytes: int) returns bool
--
-- This method reads "numBytes" from the memory address "sourceAddr"
-- and writes them to the file at "bytePos". If everything
-- was written okay, it returns TRUE; if problems it returns FALSE.
--
-- It operates on an internal buffer by calling
-- "diskDriver.SynchReadSector" and "diskDriver.SynchWriteSector".
--
var sector, offset, posInBuffer, bytesToMove: int
fcb: ptr to FileControlBlock
-- print ("--------------------\n")
-- printHexVar ("SynchWrite called sourceAddr", sourceAddr)
-- printIntVar (" bytePos", bytePos)
-- printIntVar (" numBytes", numBytes)
fileManagerLock.Lock()
if ! open || ! open.fcb || open.fcb.startingSectorOfFile < 0
FatalError ("FileManager.SynchWrite: file not properly opened")
endIf
fcb = open.fcb
while numBytes > 0
-- At this point sourceAddr and numBytes tell what work is left to do.
-- printHexVar ("NEXT MOVE:\n sourceAddr", sourceAddr)
-- printIntVar (" numBytes", numBytes)
-- printHexVar (" ", numBytes)
-- printIntVar (" startingSectorOfFile", fcb.startingSectorOfFile)
-- printIntVar (" relativeSectorInBuffer", fcb.relativeSectorInBuffer)
-- printIntVar (" bytePos", bytePos)
-- printHexVar (" ", bytePos)
sector = bytePos / PAGE_SIZE
offset = bytePos % PAGE_SIZE
-- printIntVar (" sector", sector)
-- printIntVar (" offset", offset)
-- printHexVar (" ", offset)
if fcb.relativeSectorInBuffer != sector
-- print (" calling flush\n")
self.Flush (open)
endIf
posInBuffer = fcb.bufferPtr + offset
bytesToMove = Min (numBytes, PAGE_SIZE - offset)
if fcb.relativeSectorInBuffer == sector
-- No need to read the sector first
elseIf offset == 0 && bytesToMove == PAGE_SIZE
-- No need to read the sector first
else
-- printIntVar (" READING SECTOR", sector + fcb.startingSectorOfFile)
diskDriver.SynchReadSector (sector + fcb.startingSectorOfFile,
1,
fcb.bufferPtr)
endIf
fcb.relativeSectorInBuffer = sector
fcb.bufferIsDirty = true
-- printHexVar (" MOVING - sourceAddr", sourceAddr)
-- printHexVar (" - target (posInBuffer)", posInBuffer)
-- printIntVar (" - bytesToMove", bytesToMove)
MemoryCopy (posInBuffer, sourceAddr, bytesToMove)
sourceAddr = sourceAddr + bytesToMove
bytePos = bytePos + bytesToMove
numBytes = numBytes - bytesToMove
-- printHexVar (" NEW sourceAddr", sourceAddr)
-- printIntVar (" NEW bytePos", bytePos)
-- printHexVar (" ", bytePos)
-- printIntVar (" NEW numBytes", numBytes)
-- printHexVar (" ", numBytes)
endWhile
fileManagerLock.Unlock()
-- print ("--------------------\n")
return true
endMethod
endBehavior
function copyUnalignedWord (destPtr, fromPtr: ptr to int)
var from, dest: ptr to char
from = fromPtr asPtrTo char
dest = destPtr asPtrTo char
*dest = *from
*(dest+1) = *(from+1)
*(dest+2) = *(from+2)
*(dest+3) = *(from+3)
endFunction
function printFCB (fcb: ptr to FileControlBlock)
printInt (fcb.fcbID)
printChar (' ')
endFunction
function printOpen (open: ptr to OpenFile)
print (" 0x")
printHex (open asInteger)
print (": ")
open.Print ()
endFunction
----------------------------- FileControlBlock ---------------------------------
behavior FileControlBlock
---------- FileControlBlock . Init ----------
--
-- This method is called once at startup time. It preallocates a buffer
-- in memory which may be needed when I/O is done on the file.
--
method Init ()
numberOfUsers = 0
bufferPtr = frameManager.GetAFrame ()
relativeSectorInBuffer = -1
bufferIsDirty = false
startingSectorOfFile = -1
endMethod
---------- FileControlBlock . Print ----------
method Print ()
print ("fcbID=")
printInt (fcbID)
print (", numberOfUsers=")
printInt (numberOfUsers)
print (", startingSector=")
printInt (startingSectorOfFile)
print (", sizeOfFileInBytes=")
printInt (sizeOfFileInBytes)
print (", bufferPtr=")
printHex (bufferPtr)
print (", relativeSectorInBuffer=")
printInt (relativeSectorInBuffer)
nl ()
endMethod
endBehavior
----------------------------- OpenFile ---------------------------------
behavior OpenFile
---------- OpenFile . Print ----------
method Print ()
print (" OPEN FILE: currentPos=")
printInt (currentPos)
print (", fcb=")
if fcb
fcb.Print ()
else
print ("null\n")
endIf
endMethod
---------- OpenFile . ReadBytes ----------
method ReadBytes (targetAddr, numBytes: int) returns bool
--
-- This method reads "numBytes" from this file and stores
-- them at the address pointed to by "targetAddr". If everything
-- was read okay, it returns TRUE; if problems it returns FALSE.
--
-- This method may block the caller. This method is reentrant.
--
var pos: int
-- printIntVar ("OpenFile.ReadBytes currentPos", currentPos)
fileManager.fileManagerLock.Lock ()
pos = currentPos
currentPos = currentPos + numBytes
fileManager.fileManagerLock.Unlock ()
return fileManager.SynchRead (self, targetAddr, pos, numBytes)
endMethod
---------- OpenFile . ReadInt ----------
method ReadInt () returns int
--
-- Read the next 4 bytes from a file and return it as an integer.
--
var i: int
if ! self.ReadBytes ((&i) asInteger, 4)
FatalError ("Within ReadInt: ReadBytes failed")
endIf
return i
endMethod
---------- OpenFile . LoadExecutable ----------
method LoadExecutable (addrSpace: ptr to AddrSpace) returns int
--
-- This method reads an executable "a.out" file from the disk, creates
-- a virtual address space (with all pages resident in memory), and
-- loads the executable program into the new address space.
--
-- The virtual address space will consist of (in this order):
-- The environment page(s) see NUMBER_OF_ENVIRONMENT_PAGES
-- The text page(s)
-- The data page(s)
-- The bss page(s)
-- The stack page(s) see USER_STACK_SIZE_IN_PAGES
--
-- The given "addrSpace" is assumed to be empty; this method will
-- allocate new frames and initialize the page table.
--
-- If all is okay, this method returns the initial PC, which will be
-- the address of the first word of the first text page.
--
-- If any problems arise, this method returns -1.
--
var nextVirtPage, addr: int
textSize, dataSize, bssSize, textStart, dataStart, bssStart: int
i, textSizeInPages, dataSizeInPages, bssSizeInPages: int
-- Make sure this address space is empty...
if addrSpace.numberOfPages != 0
FatalError ("LoadExecutable: This virtual address space is not empty")
endIf
-- Read and check the magic number...
if self.ReadInt () != 0x424C5A78 -- in ASCII: "BLZx"
print ("LoadExecutable: Bad magic number\n")
return -1
endIf
-- Read in the header info...
textSize = self.ReadInt ()
dataSize = self.ReadInt ()
bssSize = self.ReadInt ()
textStart = self.ReadInt ()
dataStart = self.ReadInt ()
bssStart = self.ReadInt ()
-- Compute the size of the text segment in pages...
if textSize % PAGE_SIZE != 0
print ("LoadExecutable: The text segment size not a multiple of page size\n")
return -1
endIf
textSizeInPages = textSize / PAGE_SIZE
-- Environment pages are filled in by the OS; make sure the executable
-- and the OS agree about how many there are to be...
if textStart != NUMBER_OF_ENVIRONMENT_PAGES * PAGE_SIZE
print ("LoadExecutable: The environment size does not match the 'loadAddr' info supplied to the linker\n")
return -1
endIf
-- Compute the size of the data segment in pages...
if dataSize % PAGE_SIZE != 0
print ("LoadExecutable: The data segment size not a multiple of page size\n")
return -1
endIf
if dataStart != textStart + textSize
print ("LoadExecutable: dataStart != textStart + textSize\n")
return -1
endIf
dataSizeInPages = dataSize / PAGE_SIZE
-- Compute the size of the bss segment in pages...
if bssSize % PAGE_SIZE != 0
print ("LoadExecutable: The bss segment size not a multiple of page size\n")
return -1
endIf
if bssStart != dataStart + dataSize
print ("LoadExecutable: bssStart != dataStart + dataSize\n")
return -1
endIf
bssSizeInPages = bssSize / PAGE_SIZE
-- Compute how many pages to put into the address space...
i = textSizeInPages + dataSizeInPages + bssSizeInPages +
USER_STACK_SIZE_IN_PAGES + NUMBER_OF_ENVIRONMENT_PAGES
/*****
printIntVar ("NUMBER_OF_ENVIRONMENT_PAGES", NUMBER_OF_ENVIRONMENT_PAGES)
printIntVar ("USER_STACK_SIZE_IN_PAGES", USER_STACK_SIZE_IN_PAGES)
printIntVar ("textSizeInPages", textSizeInPages)
printIntVar ("dataSizeInPages", dataSizeInPages)
printIntVar ("bssSizeInPages", bssSizeInPages)
printIntVar ("addrSpace.numberOfPages", addrSpace.numberOfPages)
printIntVar ("Number of pages in this address space", i)
printIntVar ("MAX_PAGES_PER_VIRT_SPACE", MAX_PAGES_PER_VIRT_SPACE)
*****/
-- Allocate the frames...
if i > MAX_PAGES_PER_VIRT_SPACE
print ("LoadExecutable: This virtual address space exceeds the limit\n")
printIntVar ("LoadExecutable: Number of pages in this address space", i)
printIntVar ("LoadExecutable: MAX_PAGES_PER_VIRT_SPACE", MAX_PAGES_PER_VIRT_SPACE)
return -1
endIf
frameManager.GetNewFrames (addrSpace, i)
-- print ("LoadExecutable: The address space just allocated...\n")
-- addrSpace.Print ()
-- Read and check the separator...
if self.ReadInt () != 0x2a2a2a2a
print ("LoadExecutable: Invalid file format - missing separator (1)\n")
frameManager.ReturnAllFrames (addrSpace)
return -1
endIf
-- Read the text segment...
nextVirtPage = textStart / PAGE_SIZE
for i = 1 to textSizeInPages
addr = addrSpace.ExtractFrameAddr (nextVirtPage)
-- printIntVar ("About to read; nextVirtPage", nextVirtPage)
-- printHexVar (" addr", addr)
if ! self.ReadBytes (addr, PAGE_SIZE)
print ("LoadExecutable: Problems reading from file (text)\n")
frameManager.ReturnAllFrames (addrSpace)
return -1
endIf
addrSpace.ClearWritable (nextVirtPage)
nextVirtPage = nextVirtPage + 1
endFor
-- Read and check the separator...
if self.ReadInt () != 0x2a2a2a2a
print ("LoadExecutable: Invalid file format - missing separator (2)\n")
frameManager.ReturnAllFrames (addrSpace)
return -1
endIf
-- Read the data segment...
for i = 1 to dataSizeInPages
addr = addrSpace.ExtractFrameAddr (nextVirtPage)
-- printIntVar ("About to read; nextVirtPage", nextVirtPage)
-- printHexVar (" addr", addr)
if ! self.ReadBytes (addr, PAGE_SIZE)
print ("LoadExecutable: Problems reading from file (text)\n")
frameManager.ReturnAllFrames (addrSpace)
return -1
endIf
nextVirtPage = nextVirtPage + 1
endFor
-- Read and check the separator...
if self.ReadInt () != 0x2a2a2a2a
print ("LoadExecutable: Invalid file format - missing separator (3)\n")
frameManager.ReturnAllFrames (addrSpace)
return -1
endIf
-- Zero out the bss segment...
addr = addrSpace.ExtractFrameAddr (nextVirtPage)
-- printIntVar ("About to zero bss segment; page", nextVirtPage)
-- printHexVar (" addr", addr)
-- printHexVar (" bssSizeInBytes", bssSize)
MemoryZero (addr, bssSize)
-- User programs begin execution at the first word of the text segment...
return textStart
endMethod
endBehavior
endCode
|
haominhe/Graduate
|
CS510 Operating System Foundations/P1/HelloWorld.c
|
code Hello
-- This is the "hello world" program, for use in Project 1.
function main ()
print ("Hello, world...\n")
foo (10)
endFunction
function foo (x: int)
bar (x+1)
endFunction
function bar (a: int)
var b: int
b = a + 1
print ("The value of b is ")
printInt (b)
nl ()
debug
bar (b)
endFunction
endCode
|
haominhe/Graduate
|
CS510 Operating System Foundations/P3/Main.c
|
<filename>CS510 Operating System Foundations/P3/Main.c<gh_stars>0
code Main
-- OS Class: Project 3
--
-- <NAME>
--
--
--
-- References:
-- Tanenbaum textbook, SleepingBarberProblem.pdf
-- http://users.dickinson.edu/~braught/courses/cs354s00/classes/code/SleepBarber.src.html
-- https://courses.cs.washington.edu/courses/cse451/98sp/Projects/Assign4/mipsi-solution/USER/barber.c
-- https://github.com/JuShuck
-- http://web.cecs.pdx.edu/~harry/Blitz/OSProject/p2/Main.c
-- https://github.com/tgjamin
-- https://github.com/ladinu
----------------------------- Main ---------------------------------
function main ()
InitializeScheduler ()
SleepingBarber ()
ThreadFinish ()
endFunction
----------------------------- SleepingBarber ---------------------------------
const CHAIRNUM = 5 -- # chairs for waiting customers
const CUSTOMERNUM = 10 -- 10 customers
const BARBERNUM = 1 -- 1 barber
var
customers: Semaphore = new Semaphore -- # of customers waiting for service
barbers: Semaphore = new Semaphore -- # of barbers waiting for customers
mulock: Mutex = new Mutex -- for mutual exclusion
waiting: int = 0 -- customer are waiting (not being cut)
-- 10 customers/threads. 1 barber/thread
cusArray: array [CUSTOMERNUM] of Thread = new array of Thread { CUSTOMERNUM of new Thread } -- thread for customer
barArray: array [BARBERNUM] of Thread = new array of Thread { BARBERNUM of new Thread } -- thread for barber
function SleepingBarber()
-- initialize variables
customers.Init(0) -- nothing happens yet, set semaphore to 0
barbers.Init(0)
mulock.Init() -- initialize the lock
print(" Barber 1 2 3 4 5 6 7 8 9 10 \n")
-- initialize one barber thread
barArray[0].Init("Barber")
barArray[0].Fork(barber, 1)
-- initialize 10 customer threads
cusArray[0].Init("Customer 1")
cusArray[0].Fork(CutAndWait,1)
cusArray[1].Init("Customer 2")
cusArray[1].Fork(CutAndWait,2)
cusArray[2].Init("Customer 3")
cusArray[2].Fork(CutAndWait,3)
cusArray[3].Init("Customer 4")
cusArray[3].Fork(CutAndWait,4)
cusArray[4].Init("Customer 5")
cusArray[4].Fork(CutAndWait,5)
cusArray[5].Init("Customer 6")
cusArray[5].Fork(CutAndWait,6)
cusArray[6].Init("Customer 7")
cusArray[6].Fork(CutAndWait,7)
cusArray[7].Init("Customer 8")
cusArray[7].Fork(CutAndWait,8)
cusArray[8].Init("Customer 9")
cusArray[8].Fork(CutAndWait,9)
cusArray[9].Init("Customer 10")
cusArray[9].Fork(CutAndWait,10)
endFunction
function CutAndWait (p: int)
-- The parameter "p" identifies which customer this is.
-- a customer entering the shop has to count the number of
-- waiting customers. If it is less than the number of chairs (5),
-- he stays; otherwise, he leaves.
-- There are 10 cutomers in total, we need to go around and check each customer status
-- When a customer is done haircut and left, other customer in waiting can take the seat
var
i: int
for i = 1 to 10
-- call customer function
customer(p)
endFor
endFunction
function barber()
while(true)
customers.Down() -- go to sleep if # of customers is 0, Sleep until someone arrives and wakes you
mulock.Lock() -- acquire access to "waiting", get the lock
waiting = waiting - 1 -- decrement count of waiting customers, cut current customer hair
barbers.Up() -- one barber is now ready to cut hair, wake up barber
mulock.Unlock() -- release 'waiting' lock
cut_hair() -- cut hair (outside critical region)
endWhile --
endFunction
function customer(p:int)
-- The parameter "p" identifies which customer this is.
-- get lock before enter critical section
mulock.Lock()
enterh(p) -- customer entered the barber shop
if(waiting < CHAIRNUM) -- if the customer has a place to sit, if there are no free chairs, leave
waiting = waiting + 1 -- increment count of waiting customers
sith(p) -- customer sit down
customers.Up() -- wake up barber if necessary, signal that a customer showed up
mulock.Unlock() -- release access to 'waiting'
barbers.Down() -- go to sleep if # of free barbers is 0, wait for barber
get_haircut(p) -- be seated and be served, barber is cutting hair
leaveh(p) -- get haircut done and leave
else
leaveh(p) -- if there are no free chairs, leave
mulock.Unlock() -- shop is full; do not wait
endIf
endFunction
function get_haircut(p:int)
--customer get haircut
var
i:int
mulock.Lock()
beginh(p)
for i=1 to 80
currentThread.Yield() --haircut time consuming
endFor
finishh(p) --print we are done
mulock.Unlock()
endFunction
function cut_hair()
-- cut current customer hair
-- let the current thread wait.
-- acquire lock before cutting
var
len: int
mulock.Lock()
starth() --start haircut
-- haricut consuming time 80
for len = 1 to 80
-- make other threads wait until we are done. other threads do not have the lock
currentThread.Yield()
endFor
endh() --end haircut
mulock.Unlock() -- release the lock
endFunction
-- E = Enter, S = Sit in waiting chair, B = Begin haircut, F = Finish haircut, L = Leave
-- start = Barber begins haircut, end = Barber ends haircut
function beginh(p:int)
--print begin haircut
currentchairstatus()
printspace(p)
print("B\n")
endFunction
function finishh(p:int)
-- print finish haircut
currentchairstatus()
printspace(p)
print("F\n")
endFunction
function printspace(p:int)
-- print spaces for current thread
var
i: int
print(" ")
for i = 1 to (p - 1) * 4
print("-")
endFor
endFunction
function currentchairstatus()
var
seat: int
print(" ")
-- print how many chairs occupied
for seat = 1 to waiting
print ("X")
endFor
-- how many chairs are empty
for seat = 1 to CHAIRNUM - waiting
print ("_")
endFor
print(" ")
endFunction
function starth()
currentchairstatus()
print(" start\n")
endFunction
function endh()
currentchairstatus()
print(" end\n")
endFunction
function enterh(p:int)
currentchairstatus()
printspace(p)
print("E\n")
endFunction
function sith(p:int)
currentchairstatus()
printspace(p)
print("S\n")
endFunction
function leaveh(p:int)
currentchairstatus()
printspace(p)
print("L\n")
endFunction
endCode
|
MobileChromeApps/cordova-plugin-chrome-apps-bluetooth
|
src/ios/ChromeBluetooth.h
|
@interface ChromeBluetooth : CDVPlugin {
}
#pragma mark chrome.bluetoothLowEnergy interface
// chrome.bluetooth and chrome.bluetoothLowEnergy uses same file because connect, and disconnect
// a deivce requires the same instance of CBCentralManager that found the device.
- (void)connect:(CDVInvokedUrlCommand*)command;
- (void)disconnect:(CDVInvokedUrlCommand*)command;
- (void)getService:(CDVInvokedUrlCommand*)command;
- (void)getServices:(CDVInvokedUrlCommand*)command;
- (void)getCharacteristic:(CDVInvokedUrlCommand*)command;
- (void)getCharacteristics:(CDVInvokedUrlCommand*)command;
- (void)getIncludedServices:(CDVInvokedUrlCommand*)command;
- (void)getDescriptor:(CDVInvokedUrlCommand*)command;
- (void)getDescriptors:(CDVInvokedUrlCommand*)command;
- (void)readCharacteristicValue:(CDVInvokedUrlCommand*)command;
- (void)writeCharacteristicValue:(CDVInvokedUrlCommand*)command;
- (void)startCharacteristicNotifications:(CDVInvokedUrlCommand*)command;
- (void)stopCharacteristicNotifications:(CDVInvokedUrlCommand*)command;
- (void)readDescriptorValue:(CDVInvokedUrlCommand*)command;
- (void)writeDescriptorValue:(CDVInvokedUrlCommand*)command;
- (void)registerBluetoothLowEnergyEvents:(CDVInvokedUrlCommand*)command;
@end
|
alexw91/aws-c-compression
|
tests/fuzz/transitive.c
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/compression/huffman.h>
#include <aws/compression/private/huffman_testing.h>
#include <aws/testing/aws_test_harness.h>
struct aws_huffman_symbol_coder *test_get_coder(void);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (!size) {
return 0;
}
const char *error_message = NULL;
int result = huffman_test_transitive(test_get_coder(), (const char *)data, size, 0, &error_message);
ASSERT_SUCCESS(result, error_message);
return 0; // Non-zero return values are reserved for future use.
}
|
alexw91/aws-c-compression
|
tests/library_test.c
|
<filename>tests/library_test.c
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/compression/compression.h>
#include <aws/testing/aws_test_harness.h>
AWS_TEST_CASE(library_init, s_test_library_init)
static int s_test_library_init(struct aws_allocator *allocator, void *ctx) {
(void)ctx;
aws_compression_library_init(allocator);
/* Ensure that errors were registered */
const char *err_name = aws_error_name(AWS_ERROR_COMPRESSION_UNKNOWN_SYMBOL);
const char *expected = "AWS_ERROR_COMPRESSION_UNKNOWN_SYMBOL";
ASSERT_BIN_ARRAYS_EQUALS(expected, strlen(expected), err_name, strlen(err_name));
aws_compression_library_clean_up();
return AWS_OP_SUCCESS;
}
|
alexw91/aws-c-compression
|
source/compression.c
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/compression/compression.h>
#define DEFINE_ERROR_INFO(CODE, STR) \
[(CODE)-AWS_ERROR_ENUM_BEGIN_RANGE(AWS_C_COMPRESSION_PACKAGE_ID)] = \
AWS_DEFINE_ERROR_INFO(CODE, STR, "aws-c-compression")
/* clang-format off */
static struct aws_error_info s_errors[] = {
DEFINE_ERROR_INFO(
AWS_ERROR_COMPRESSION_UNKNOWN_SYMBOL,
"Compression encountered an unknown symbol."),
};
/* clang-format on */
static struct aws_error_info_list s_error_list = {
.error_list = s_errors,
.count = AWS_ARRAY_SIZE(s_errors),
};
static bool s_library_initialized = false;
void aws_compression_library_init(struct aws_allocator *alloc) {
if (s_library_initialized) {
return;
}
s_library_initialized = true;
aws_common_library_init(alloc);
aws_register_error_info(&s_error_list);
}
void aws_compression_library_clean_up(void) {
if (!s_library_initialized) {
return;
}
s_library_initialized = false;
aws_unregister_error_info(&s_error_list);
aws_common_library_clean_up();
}
|
alexw91/aws-c-compression
|
tests/fuzz/decode.c
|
<gh_stars>10-100
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/compression/huffman.h>
#include <aws/compression/private/huffman_testing.h>
#include <aws/testing/aws_test_harness.h>
struct aws_huffman_symbol_coder *test_get_coder(void);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (!size) {
return 0;
}
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, test_get_coder());
size_t output_buffer_size = size * 2;
char output_buffer[output_buffer_size];
struct aws_byte_cursor to_decode = aws_byte_cursor_from_array(data, size);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, AWS_ARRAY_SIZE(output_buffer));
/* Don't really care about result, just make sure there's no crash */
aws_huffman_decode(&decoder, &to_decode, &output_buf);
return 0; // Non-zero return values are reserved for future use.
}
|
alexw91/aws-c-compression
|
source/huffman_testing.c
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
/**
* See aws/testing/compression/huffman.h for docs.
*/
#define AWS_UNSTABLE_TESTING_API
#include <aws/compression/private/huffman_testing.h>
#include <aws/common/byte_buf.h>
#include <aws/common/common.h>
int huffman_test_transitive(
struct aws_huffman_symbol_coder *coder,
const char *input,
size_t size,
size_t encoded_size,
const char **error_string) {
struct aws_huffman_encoder encoder;
aws_huffman_encoder_init(&encoder, coder);
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, coder);
const size_t intermediate_buffer_size = size * 2;
AWS_VARIABLE_LENGTH_ARRAY(uint8_t, intermediate_buffer, intermediate_buffer_size);
memset(intermediate_buffer, 0, intermediate_buffer_size);
AWS_VARIABLE_LENGTH_ARRAY(char, output_buffer, size);
memset(output_buffer, 0, size);
struct aws_byte_cursor to_encode = aws_byte_cursor_from_array((uint8_t *)input, size);
struct aws_byte_buf intermediate_buf = aws_byte_buf_from_empty_array(intermediate_buffer, intermediate_buffer_size);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, size);
int result = aws_huffman_encode(&encoder, &to_encode, &intermediate_buf);
if (result != AWS_OP_SUCCESS) {
*error_string = "aws_huffman_encode failed";
return AWS_OP_ERR;
}
if (to_encode.len != 0) {
*error_string = "not all data encoded";
return AWS_OP_ERR;
}
if (encoded_size && intermediate_buf.len != encoded_size) {
*error_string = "encoded length is incorrect";
return AWS_OP_ERR;
}
struct aws_byte_cursor intermediate_cur = aws_byte_cursor_from_buf(&intermediate_buf);
result = aws_huffman_decode(&decoder, &intermediate_cur, &output_buf);
if (result != AWS_OP_SUCCESS) {
*error_string = "aws_huffman_decode failed";
return AWS_OP_ERR;
}
if (intermediate_cur.len != 0) {
*error_string = "not all encoded data was decoded";
return AWS_OP_ERR;
}
if (output_buf.len != size) {
*error_string = "decode output size incorrect";
return AWS_OP_ERR;
}
if (memcmp(input, output_buffer, size) != 0) {
*error_string = "decoded data does not match input data";
return AWS_OP_ERR;
}
return AWS_OP_SUCCESS;
}
int huffman_test_transitive_chunked(
struct aws_huffman_symbol_coder *coder,
const char *input,
size_t size,
size_t encoded_size,
size_t output_chunk_size,
const char **error_string) {
struct aws_huffman_encoder encoder;
aws_huffman_encoder_init(&encoder, coder);
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, coder);
const size_t intermediate_buffer_size = size * 2;
AWS_VARIABLE_LENGTH_ARRAY(uint8_t, intermediate_buffer, intermediate_buffer_size);
memset(intermediate_buffer, 0, intermediate_buffer_size);
AWS_VARIABLE_LENGTH_ARRAY(char, output_buffer, size);
memset(output_buffer, 0, size);
struct aws_byte_cursor to_encode = aws_byte_cursor_from_array(input, size);
struct aws_byte_buf intermediate_buf = aws_byte_buf_from_empty_array(intermediate_buffer, (size_t)-1);
intermediate_buf.capacity = 0;
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, (size_t)-1);
output_buf.capacity = 0;
int result = AWS_OP_SUCCESS;
{
do {
const size_t previous_intermediate_len = intermediate_buf.len;
intermediate_buf.capacity += output_chunk_size;
result = aws_huffman_encode(&encoder, &to_encode, &intermediate_buf);
if (intermediate_buf.len == previous_intermediate_len) {
*error_string = "encode didn't write any data";
return AWS_OP_ERR;
}
if (result != AWS_OP_SUCCESS && aws_last_error() != AWS_ERROR_SHORT_BUFFER) {
*error_string = "encode returned wrong error code";
return AWS_OP_ERR;
}
} while (result != AWS_OP_SUCCESS);
}
if (result != AWS_OP_SUCCESS) {
*error_string = "aws_huffman_encode failed";
return AWS_OP_ERR;
}
if (intermediate_buf.len > intermediate_buffer_size) {
*error_string = "too much data encoded";
return AWS_OP_ERR;
}
if (encoded_size && intermediate_buf.len != encoded_size) {
*error_string = "encoded length is incorrect";
return AWS_OP_ERR;
}
struct aws_byte_cursor intermediate_cur = aws_byte_cursor_from_buf(&intermediate_buf);
{
do {
const size_t previous_output_len = output_buf.len;
output_buf.capacity += output_chunk_size;
if (output_buf.capacity > size) {
output_buf.capacity = size;
}
result = aws_huffman_decode(&decoder, &intermediate_cur, &output_buf);
if (output_buf.len == previous_output_len) {
*error_string = "decode didn't write any data";
return AWS_OP_ERR;
}
if (result != AWS_OP_SUCCESS && aws_last_error() != AWS_ERROR_SHORT_BUFFER) {
*error_string = "decode returned wrong error code";
return AWS_OP_ERR;
}
} while (result != AWS_OP_SUCCESS);
}
if (result != AWS_OP_SUCCESS) {
*error_string = "aws_huffman_decode failed";
return AWS_OP_ERR;
}
if (output_buf.len != size) {
*error_string = "decode output size incorrect";
return AWS_OP_ERR;
}
if (memcmp(input, output_buffer, size) != 0) {
*error_string = "decoded data does not match input data";
return AWS_OP_ERR;
}
return AWS_OP_SUCCESS;
}
|
alexw91/aws-c-compression
|
tests/huffman_test.c
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/compression/private/huffman_testing.h>
#include <aws/testing/aws_test_harness.h>
#include <aws/compression/huffman.h>
/* Exported by generated file */
struct aws_huffman_symbol_coder *test_get_coder(void);
static struct huffman_test_code_point s_code_points[] = {
#include "test_huffman_static_table.def"
};
enum { NUM_CODE_POINTS = sizeof(s_code_points) / sizeof(s_code_points[0]) };
/* Useful data for testing */
static const char s_url_string[] = "www.example.com";
enum { URL_STRING_LEN = sizeof(s_url_string) - 1 };
static uint8_t s_encoded_url[] = {0x9e, 0x79, 0xeb, 0x9b, 0x04, 0xb3, 0x5a, 0x94, 0xd5, 0xe0, 0x4c, 0xdf};
enum { ENCODED_URL_LEN = sizeof(s_encoded_url) };
static const char s_all_codes[] = " !\"#$%&'()*+,-./"
"0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ["
"\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
enum { ALL_CODES_LEN = sizeof(s_all_codes) - 1 };
static uint8_t s_encoded_codes[] = {
0x26, 0x9b, 0xa7, 0x69, 0xfa, 0x86, 0xa3, 0xa9, 0x56, 0xd4, 0xf5, 0x4d, 0x57, 0x56, 0xb9, 0xc4, 0x57, 0xd5,
0xf5, 0x8d, 0x67, 0x5a, 0xd6, 0xf5, 0xcd, 0x77, 0x5e, 0xd7, 0xf6, 0x0d, 0x87, 0x62, 0xd8, 0xf6, 0x4d, 0x97,
0x66, 0xba, 0xd9, 0xf6, 0x8b, 0xbc, 0x4e, 0x2b, 0x17, 0x8c, 0xc6, 0xe3, 0xaf, 0x36, 0x9d, 0xab, 0x1f, 0x90,
0xda, 0xf6, 0xcc, 0x8e, 0xdb, 0xb7, 0x6d, 0xf7, 0xbb, 0x86, 0x4a, 0xfb, 0x71, 0xc9, 0xee, 0x5b, 0x9e, 0xe9,
0xba, 0xee, 0xdb, 0xbe, 0xf0, 0x5b, 0x10, 0x42, 0x68, 0xac, 0xc6, 0x7b, 0xf9, 0x25, 0x99, 0x09, 0xb5, 0x94,
0x52, 0xd8, 0xdc, 0x09, 0xf0, 0x68, 0xde, 0x77, 0xad, 0xef, 0x7c, 0xdf, 0x7f};
enum { ENCODED_CODES_LEN = sizeof(s_encoded_codes) };
static const size_t s_step_sizes[] = {1, 2, 4, 8, 16, 32, 64, 128};
enum { NUM_STEP_SIZES = sizeof(s_step_sizes) / sizeof(s_step_sizes[0]) };
AWS_TEST_CASE(huffman_symbol_encoder, test_huffman_symbol_encoder)
static int test_huffman_symbol_encoder(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding each character */
struct aws_huffman_symbol_coder *coder = test_get_coder();
for (size_t i = 0; i < NUM_CODE_POINTS; ++i) {
struct huffman_test_code_point *value = &s_code_points[i];
struct aws_huffman_code code = coder->encode(value->symbol, NULL);
ASSERT_UINT_EQUALS(value->code.pattern, code.pattern);
ASSERT_UINT_EQUALS(value->code.num_bits, code.num_bits);
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_encoder, test_huffman_encoder)
static int test_huffman_encoder(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding a short url */
uint8_t output_buffer[ENCODED_URL_LEN + 1];
AWS_ZERO_ARRAY(output_buffer);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, ENCODED_URL_LEN);
struct aws_huffman_symbol_coder *coder = test_get_coder();
struct aws_huffman_encoder encoder;
aws_huffman_encoder_init(&encoder, coder);
struct aws_byte_cursor to_encode = aws_byte_cursor_from_array(s_url_string, URL_STRING_LEN);
const size_t encoded_length = aws_huffman_get_encoded_length(&encoder, to_encode);
ASSERT_UINT_EQUALS(ENCODED_URL_LEN, encoded_length);
int result = aws_huffman_encode(&encoder, &to_encode, &output_buf);
ASSERT_SUCCESS(result);
ASSERT_UINT_EQUALS(ENCODED_URL_LEN, output_buf.len);
ASSERT_UINT_EQUALS(0, output_buffer[ENCODED_URL_LEN]);
ASSERT_BIN_ARRAYS_EQUALS(s_encoded_url, ENCODED_URL_LEN, output_buf.buffer, output_buf.len);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_encoder_all_code_points, test_huffman_encoder_all_code_points)
static int test_huffman_encoder_all_code_points(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding a sequence of all character values expressable as
* characters */
uint8_t output_buffer[ENCODED_CODES_LEN + 1];
AWS_ZERO_ARRAY(output_buffer);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, ENCODED_CODES_LEN);
struct aws_huffman_symbol_coder *coder = test_get_coder();
struct aws_huffman_encoder encoder;
aws_huffman_encoder_init(&encoder, coder);
struct aws_byte_cursor to_encode = aws_byte_cursor_from_array(s_all_codes, ALL_CODES_LEN);
const size_t encoded_length = aws_huffman_get_encoded_length(&encoder, to_encode);
ASSERT_UINT_EQUALS(ENCODED_CODES_LEN, encoded_length);
int result = aws_huffman_encode(&encoder, &to_encode, &output_buf);
ASSERT_SUCCESS(result);
ASSERT_UINT_EQUALS(ENCODED_CODES_LEN, output_buf.len);
ASSERT_UINT_EQUALS(0, output_buffer[ENCODED_CODES_LEN]);
ASSERT_BIN_ARRAYS_EQUALS(s_encoded_codes, ENCODED_CODES_LEN, output_buf.buffer, output_buf.len);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_encoder_partial_output, test_huffman_encoder_partial_output)
static int test_huffman_encoder_partial_output(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding when the output buffer size is limited */
struct aws_huffman_encoder encoder;
aws_huffman_encoder_init(&encoder, test_get_coder());
uint8_t output_buffer[ENCODED_CODES_LEN];
for (size_t i = 0; i < NUM_STEP_SIZES; ++i) {
const size_t step_size = s_step_sizes[i];
aws_huffman_encoder_reset(&encoder);
struct aws_byte_cursor to_encode = aws_byte_cursor_from_array(s_all_codes, ALL_CODES_LEN);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, (size_t)-1);
output_buf.capacity = 0;
AWS_ZERO_ARRAY(output_buffer);
do {
output_buf.capacity += step_size;
if (output_buf.capacity > ENCODED_CODES_LEN) {
output_buf.capacity = ENCODED_CODES_LEN;
}
const size_t previous_output_len = output_buf.len;
int result = aws_huffman_encode(&encoder, &to_encode, &output_buf);
ASSERT_TRUE(output_buf.len > previous_output_len);
ASSERT_BIN_ARRAYS_EQUALS(s_encoded_codes, output_buf.len, output_buf.buffer, output_buf.len);
if (output_buf.len == ENCODED_CODES_LEN) {
ASSERT_SUCCESS(result);
} else {
ASSERT_UINT_EQUALS(AWS_ERROR_SHORT_BUFFER, aws_last_error());
aws_reset_error();
}
} while (output_buf.len < ENCODED_CODES_LEN);
ASSERT_UINT_EQUALS(ENCODED_CODES_LEN, output_buf.len);
ASSERT_BIN_ARRAYS_EQUALS(s_encoded_codes, ENCODED_CODES_LEN, output_buf.buffer, output_buf.len);
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_encoder_exact_output, test_huffman_encoder_exact_output)
static int test_huffman_encoder_exact_output(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding when the output buffer size is exactly the necessary size */
struct aws_huffman_encoder encoder;
aws_huffman_encoder_init(&encoder, test_get_coder());
uint8_t output_buffer[2];
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, 2);
/* Encode a character that uses 8 bits into a 1 byte buffer */
struct aws_byte_cursor to_encode = aws_byte_cursor_from_array("?", 1);
uint8_t expected_1byte[] = {0xba};
output_buf.capacity = 1;
ASSERT_SUCCESS(aws_huffman_encode(&encoder, &to_encode, &output_buf));
ASSERT_BIN_ARRAYS_EQUALS(expected_1byte, 1, output_buf.buffer, output_buf.len);
/* Encode 2 characters that sum to 16 bits, into a 2 byte buffer
* y: 101000
* z: 1101111001
* combined: 1010001101111001 == 0xa379 */
to_encode = aws_byte_cursor_from_array("yz", 2);
uint8_t expected_2byte[] = {0xa3, 0x79};
output_buf.capacity = 2;
aws_byte_buf_reset(&output_buf, true /*zero*/);
ASSERT_SUCCESS(aws_huffman_encode(&encoder, &to_encode, &output_buf));
ASSERT_BIN_ARRAYS_EQUALS(expected_2byte, 2, output_buf.buffer, output_buf.len);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_symbol_decoder, test_huffman_symbol_decoder)
static int test_huffman_symbol_decoder(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test decoding each character */
struct aws_huffman_symbol_coder *coder = test_get_coder();
for (size_t i = 0; i < NUM_CODE_POINTS; ++i) {
struct huffman_test_code_point *value = &s_code_points[i];
uint32_t bit_pattern = value->code.pattern << (32 - value->code.num_bits);
uint8_t out;
size_t bits_read = coder->decode(bit_pattern, &out, NULL);
ASSERT_UINT_EQUALS(value->symbol, out);
ASSERT_UINT_EQUALS(value->code.num_bits, bits_read);
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_decoder, test_huffman_decoder)
static int test_huffman_decoder(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test decoding a short url */
char output_buffer[URL_STRING_LEN + 1];
AWS_ZERO_ARRAY(output_buffer);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, URL_STRING_LEN);
struct aws_huffman_symbol_coder *coder = test_get_coder();
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, coder);
struct aws_byte_cursor to_decode = aws_byte_cursor_from_array(s_encoded_url, ENCODED_URL_LEN);
int result = aws_huffman_decode(&decoder, &to_decode, &output_buf);
ASSERT_SUCCESS(result);
ASSERT_UINT_EQUALS(URL_STRING_LEN, output_buf.len);
ASSERT_UINT_EQUALS(0, to_decode.len);
ASSERT_UINT_EQUALS(output_buffer[URL_STRING_LEN], 0);
ASSERT_BIN_ARRAYS_EQUALS(s_url_string, URL_STRING_LEN, output_buf.buffer, output_buf.len);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_decoder_all_code_points, test_huffman_decoder_all_code_points)
static int test_huffman_decoder_all_code_points(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test decoding a sequence of all character values expressable as
* characters */
char output_buffer[ALL_CODES_LEN + 1];
AWS_ZERO_ARRAY(output_buffer);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, ALL_CODES_LEN);
struct aws_huffman_symbol_coder *coder = test_get_coder();
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, coder);
struct aws_byte_cursor to_decode = aws_byte_cursor_from_array(s_encoded_codes, ENCODED_CODES_LEN);
int result = aws_huffman_decode(&decoder, &to_decode, &output_buf);
ASSERT_SUCCESS(result);
ASSERT_UINT_EQUALS(ALL_CODES_LEN, output_buf.len);
ASSERT_UINT_EQUALS(0, to_decode.len);
ASSERT_UINT_EQUALS(output_buffer[ALL_CODES_LEN], 0);
ASSERT_BIN_ARRAYS_EQUALS(s_all_codes, ALL_CODES_LEN, output_buf.buffer, output_buf.len);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_decoder_partial_input, test_huffman_decoder_partial_input)
static int test_huffman_decoder_partial_input(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test decoding a buffer in chunks */
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, test_get_coder());
char output_buffer[150];
for (size_t i = 0; i < NUM_STEP_SIZES; ++i) {
const size_t step_size = s_step_sizes[i];
aws_huffman_decoder_reset(&decoder);
struct aws_byte_cursor to_decode = aws_byte_cursor_from_array(s_encoded_codes, ENCODED_CODES_LEN);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, ALL_CODES_LEN);
AWS_ZERO_ARRAY(output_buffer);
do {
const size_t chunk_size = step_size < to_decode.len ? step_size : to_decode.len;
struct aws_byte_cursor to_decode_chunk = aws_byte_cursor_advance(&to_decode, chunk_size);
int result = aws_huffman_decode(&decoder, &to_decode_chunk, &output_buf);
ASSERT_UINT_EQUALS(0, to_decode_chunk.len);
ASSERT_BIN_ARRAYS_EQUALS(s_all_codes, output_buf.len, output_buf.buffer, output_buf.len);
if (output_buf.len == ALL_CODES_LEN) {
ASSERT_SUCCESS(result);
}
} while (output_buf.len < ALL_CODES_LEN);
ASSERT_UINT_EQUALS(ALL_CODES_LEN, output_buf.len);
ASSERT_BIN_ARRAYS_EQUALS(s_all_codes, ALL_CODES_LEN, output_buf.buffer, output_buf.len);
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_decoder_partial_output, test_huffman_decoder_partial_output)
static int test_huffman_decoder_partial_output(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test decoding when the output buffer size is limited */
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, test_get_coder());
char output_buffer[150];
for (size_t i = 0; i < NUM_STEP_SIZES; ++i) {
const size_t step_size = s_step_sizes[i];
aws_huffman_decoder_reset(&decoder);
struct aws_byte_cursor to_decode = aws_byte_cursor_from_array(s_encoded_codes, ENCODED_CODES_LEN);
struct aws_byte_buf output_buf = aws_byte_buf_from_empty_array(output_buffer, (size_t)-1);
output_buf.capacity = 0; /* Can't set above because it sets buffer to 0 */
AWS_ZERO_ARRAY(output_buffer);
do {
output_buf.capacity += step_size;
if (output_buf.capacity > ALL_CODES_LEN) {
output_buf.capacity = ALL_CODES_LEN;
}
const size_t previous_output_size = output_buf.len;
int result = aws_huffman_decode(&decoder, &to_decode, &output_buf);
ASSERT_TRUE(output_buf.len > previous_output_size);
ASSERT_BIN_ARRAYS_EQUALS(s_all_codes, output_buf.len, output_buf.buffer, output_buf.len);
if (output_buf.len == ALL_CODES_LEN) {
ASSERT_SUCCESS(result);
} else {
ASSERT_UINT_EQUALS(AWS_ERROR_SHORT_BUFFER, aws_last_error());
aws_reset_error();
}
} while (output_buf.len < ALL_CODES_LEN);
ASSERT_UINT_EQUALS(ALL_CODES_LEN, output_buf.len);
ASSERT_BIN_ARRAYS_EQUALS(s_all_codes, ALL_CODES_LEN, output_buf.buffer, output_buf.len);
}
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_decoder_allow_growth, test_huffman_decoder_allow_growth)
static int test_huffman_decoder_allow_growth(struct aws_allocator *allocator, void *ctx) {
(void)ctx;
/* Test that decoder will grow output buffer if allow-growth is set */
struct aws_huffman_decoder decoder;
aws_huffman_decoder_init(&decoder, test_get_coder());
aws_huffman_decoder_allow_growth(&decoder, true);
struct aws_byte_buf output_buf;
ASSERT_SUCCESS(aws_byte_buf_init(&output_buf, allocator, 1 /* way too small */));
struct aws_byte_cursor to_decode = aws_byte_cursor_from_array(s_encoded_url, ENCODED_URL_LEN);
ASSERT_SUCCESS(aws_huffman_decode(&decoder, &to_decode, &output_buf));
ASSERT_UINT_EQUALS(0, to_decode.len);
ASSERT_BIN_ARRAYS_EQUALS(s_url_string, URL_STRING_LEN, output_buf.buffer, output_buf.len);
aws_byte_buf_clean_up(&output_buf);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_transitive, test_huffman_transitive)
static int test_huffman_transitive(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding a short url and immediately decoding it */
const char *error_message = NULL;
int result =
huffman_test_transitive(test_get_coder(), s_url_string, URL_STRING_LEN, ENCODED_URL_LEN, &error_message);
ASSERT_SUCCESS(result, error_message);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_transitive_even_bytes, test_huffman_transitive_even_bytes)
static int test_huffman_transitive_even_bytes(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding a string that encodes to a multiple of 8 bits */
const char *error_message = NULL;
int result = huffman_test_transitive(test_get_coder(), "cdfh", 4, 3, &error_message);
ASSERT_SUCCESS(result, error_message);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_transitive_all_code_points, test_huffman_transitive_all_code_points)
static int test_huffman_transitive_all_code_points(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding a sequence of all character values expressable as
* characters and immediately decoding it */
const char *error_message = NULL;
int result =
huffman_test_transitive(test_get_coder(), s_all_codes, ALL_CODES_LEN, ENCODED_CODES_LEN, &error_message);
ASSERT_SUCCESS(result, error_message);
return AWS_OP_SUCCESS;
}
AWS_TEST_CASE(huffman_transitive_chunked, test_huffman_transitive_chunked)
static int test_huffman_transitive_chunked(struct aws_allocator *allocator, void *ctx) {
(void)allocator;
(void)ctx;
/* Test encoding a sequence of all character values expressable as
* characters and immediately decoding it */
for (size_t i = 0; i < NUM_STEP_SIZES; ++i) {
const size_t step_size = s_step_sizes[i];
const char *error_message = NULL;
int result = huffman_test_transitive_chunked(
test_get_coder(), s_all_codes, ALL_CODES_LEN, ENCODED_CODES_LEN, step_size, &error_message);
ASSERT_SUCCESS(result, error_message);
}
return AWS_OP_SUCCESS;
}
|
alexw91/aws-c-compression
|
source/huffman_generator/generator.c
|
<filename>source/huffman_generator/generator.c
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <assert.h> /* NOLINT(fuchsia-restrict-system-includes) */
#include <aws/common/file.h>
#include <ctype.h>
#include <stdint.h> /* NOLINT(fuchsia-restrict-system-includes) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct huffman_code {
uint8_t num_bits;
uint32_t bits;
};
struct huffman_code_point {
uint8_t symbol;
struct huffman_code code;
};
enum { num_code_points = 256 };
static struct huffman_code_point code_points[num_code_points];
static size_t skip_whitespace(const char *str) {
size_t offset = 0;
while (str[offset] == ' ' || str[offset] == '\t') {
++offset;
}
return offset;
}
static size_t read_past_comma(const char *str) {
size_t offset = 0;
while (str[offset] != ',') {
++offset;
}
return offset + 1;
}
int read_code_points(const char *input_path) {
memset(code_points, 0, sizeof(code_points));
FILE *file = aws_fopen(input_path, "r");
if (!file) {
printf("Failed to open file '%s' for read.", input_path);
return 1;
}
static const char HC_KEYWORD[] = "HUFFMAN_CODE";
static const size_t HC_KW_LEN = sizeof(HC_KEYWORD) - 1;
int is_comment = 0;
char line[120];
while (fgets(line, sizeof(line), file) != NULL) {
const size_t line_length = strlen(line);
if (line[0] == '#') {
/* Ignore preprocessor directives */
continue;
}
for (size_t i = 0; i < line_length - 1; ++i) {
if (!is_comment) {
if (line[i] == '/' && line[i + 1] == '*') {
is_comment = 1;
} else if (strncmp(&line[i], HC_KEYWORD, HC_KW_LEN) == 0) {
/* Found code, parse it */
/* Skip macro */
const char *current_char = &line[i + HC_KW_LEN];
current_char += skip_whitespace(current_char);
/* Skip ( */
assert(*current_char == '(');
++current_char;
/* Parse symbol */
uint8_t symbol = (uint8_t)atoi(current_char);
struct huffman_code_point *code_point = &code_points[symbol];
assert(!code_point->symbol && "Symbol already found!");
code_point->symbol = symbol;
current_char += read_past_comma(current_char);
/* Skip the binary string form */
current_char += read_past_comma(current_char);
/* Parse bits */
code_point->code.bits = (uint32_t)strtol(current_char, NULL, 16);
current_char += read_past_comma(current_char);
code_point->code.num_bits = (uint8_t)atoi(current_char);
}
} else if (line[i] == '*' && line[i + 1] == '/') {
is_comment = 0;
}
}
}
fclose(file);
return 0;
}
void code_write(struct huffman_code *code, FILE *file) {
for (int bit_idx = code->num_bits - 1; bit_idx >= 0; --bit_idx) {
char bit = ((code->bits >> bit_idx) & 0x1) ? '1' : '0';
fprintf(file, "%c", bit);
}
}
struct huffman_node {
struct huffman_code_point *value;
struct huffman_code code;
struct huffman_node *children[2];
};
struct huffman_node *huffman_node_new(struct huffman_code code) {
struct huffman_node *node = malloc(sizeof(struct huffman_node));
memset(node, 0, sizeof(struct huffman_node));
node->code = code;
return node;
}
struct huffman_node *huffman_node_new_value(struct huffman_code_point *value) {
struct huffman_node *node = malloc(sizeof(struct huffman_node));
memset(node, 0, sizeof(struct huffman_node));
node->value = value;
node->code = value->code;
return node;
}
/* note: Does not actually free the memory.
This is useful so this function may be called on the tree root. */
void huffman_node_clean_up(struct huffman_node *node) {
for (int i = 0; i < 2; ++i) {
if (node->children[i]) {
huffman_node_clean_up(node->children[i]);
free(node->children[i]);
}
}
memset(node, 0, sizeof(struct huffman_node));
}
/* This function writes what to do if the pattern for node is a match */
void huffman_node_write_decode_handle_value(struct huffman_node *node, FILE *file) {
if (!node) {
/* Invalid node, return 0 */
fprintf(file, " return 0; /* invalid node */\n");
} else if (node->value) {
/* Attempt to inline value return */
fprintf(
file,
" *symbol = %u;\n"
" return %u;\n",
node->value->symbol,
node->value->code.num_bits);
} else {
/* Otherwise go to branch check */
fprintf(file, " goto node_");
code_write(&node->code, file);
fprintf(file, ";\n");
}
}
void huffman_node_write_decode(struct huffman_node *node, FILE *file, uint8_t current_bit) {
/* Value nodes should have been inlined into parent branch checks */
assert(!node->value);
assert(node->children[0] || node->children[1]);
static int write_label = 0;
if (write_label) {
/* Write this node's label after the first run */
fprintf(file, "node_");
code_write(&node->code, file);
fprintf(file, ":\n");
}
write_label = 1;
/* Check 1 bit pattern */
uint32_t single_bit_mask = (uint32_t)(1ull << (31 - current_bit));
uint32_t left_aligned_pattern = ((node->code.bits << 1) + 1) << (31 - node->code.num_bits);
uint32_t check_pattern = left_aligned_pattern & single_bit_mask;
fprintf(file, " if (bits & 0x%x) {\n", check_pattern);
huffman_node_write_decode_handle_value(node->children[1], file);
fprintf(file, " } else {\n");
/* Child 0 is valid, go there */
huffman_node_write_decode_handle_value(node->children[0], file);
fprintf(file, " }\n\n");
/* Recursively write child nodes */
for (uint8_t i = 0; i < 2; ++i) {
struct huffman_node *child = node->children[i];
if (child && !child->value) {
huffman_node_write_decode(child, file, current_bit + 1);
}
}
}
int main(int argc, char *argv[]) {
if (argc != 4) {
fprintf(
stderr,
"generator expects 3 arguments: [input file] [output file] "
"[encoding name]\n"
"A function of the following signature will be exported:\n"
"struct aws_huffman_symbol_coder *[encoding name]_get_coder()\n");
return 1;
}
const char *input_file = argv[1];
const char *output_file = argv[2];
const char *decoder_name = argv[3];
if (read_code_points(input_file)) {
return 1;
}
struct huffman_node tree_root;
memset(&tree_root, 0, sizeof(struct huffman_node));
/* Populate the tree */
for (size_t i = 0; i < num_code_points; ++i) {
struct huffman_code_point *value = &code_points[i];
if (value->code.num_bits == 0) {
continue;
}
struct huffman_node *current = &tree_root;
uint8_t bit_idx = value->code.num_bits - 1;
while (1) {
struct huffman_code code = value->code;
code.bits >>= bit_idx;
code.num_bits = value->code.num_bits - bit_idx;
uint8_t encoded_bit = code.bits & 0x01;
assert(encoded_bit == 0 || encoded_bit == 1);
if (bit_idx == 0) {
/* Done traversing, add value as leaf */
assert(!current->children[encoded_bit]);
current->children[encoded_bit] = huffman_node_new_value(value);
break;
}
if (current->children[encoded_bit]) {
/* Not at the end yet, keep traversing */
current = current->children[encoded_bit];
} else {
/* Not at the end yet, but this is the first time down this
* path. */
struct huffman_node *new_node = huffman_node_new(code);
current->children[encoded_bit] = new_node;
current = new_node;
}
--bit_idx;
}
}
/* Open the file */
FILE *file = aws_fopen(output_file, "w");
if (!file) {
printf("Failed to open file '%s' for write.", output_file);
return 1;
}
/* Write the file/function header */
fprintf(
file,
"/**\n"
" * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n"
" * SPDX-License-Identifier: Apache-2.0.\n"
" */\n"
"\n"
"/* WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT. */\n"
"/* clang-format off */\n"
"\n"
"#include <aws/compression/huffman.h>\n"
"\n"
"static struct aws_huffman_code code_points[] = {\n");
for (size_t i = 0; i < num_code_points; ++i) {
struct huffman_code_point *cp = &code_points[i];
fprintf(
file,
" { .pattern = 0x%x, .num_bits = %u }, /* '%c' %u */\n",
cp->code.bits,
cp->code.num_bits,
isprint(cp->symbol) ? cp->symbol : ' ',
cp->symbol);
}
fprintf(
file,
"};\n"
"\n"
"static struct aws_huffman_code encode_symbol(uint8_t symbol, void "
"*userdata) {\n"
" (void)userdata;\n\n"
" return code_points[symbol];\n"
"}\n"
"\n"
"/* NOLINTNEXTLINE(readability-function-size) */\n"
"static uint8_t decode_symbol(uint32_t bits, uint8_t *symbol, void "
"*userdata) {\n"
" (void)userdata;\n\n");
/* Traverse the tree */
huffman_node_write_decode(&tree_root, file, 0);
/* Write the function footer & encode header */
fprintf(
file,
"}\n"
"\n"
"struct aws_huffman_symbol_coder *%s_get_coder(void) {\n"
"\n"
" static struct aws_huffman_symbol_coder coder = {\n"
" .encode = encode_symbol,\n"
" .decode = decode_symbol,\n"
" .userdata = NULL,\n"
" };\n"
" return &coder;\n"
"}\n",
decoder_name);
fclose(file);
huffman_node_clean_up(&tree_root);
return 0;
}
|
alexw91/aws-c-compression
|
tests/fuzz/transitive_chunked.c
|
<gh_stars>10-100
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/compression/huffman.h>
#include <aws/compression/private/huffman_testing.h>
#include <aws/testing/aws_test_harness.h>
struct aws_huffman_symbol_coder *test_get_coder(void);
int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (!size) {
return 0;
}
static const size_t step_sizes[] = {1, 2, 4, 8, 16, 32, 64, 128};
for (size_t i = 0; i < sizeof(step_sizes) / sizeof(size_t); ++i) {
size_t step_size = step_sizes[i];
const char *error_message = NULL;
int result =
huffman_test_transitive_chunked(test_get_coder(), (const char *)data, size, 0, step_size, &error_message);
ASSERT_SUCCESS(result, error_message);
}
return 0; // Non-zero return values are reserved for future use.
}
|
lst60916/Position_Based_Dynamics
|
PositionBasedDynamics/PositionBasedElasticRods.h
|
#ifndef POSITION_BASED_ELASTIC_RODS_H
#define POSITION_BASED_ELASTIC_RODS_H
#include <Eigen/Dense>
#include "Common/Common.h"
// ------------------------------------------------------------------------------------
namespace PBD
{
// Implementation of "Position Based Elastic Rods" paper
// (http://www.nobuyuki-umetani.com/PositionBasedElasticRod/2014_sca_PositionBasedElasticRod.html)
//
// The code is based on the implementation of
//
// <NAME>
// Department of Surgery and Cancer
// Imperial College London
//
// http://github.com/korzen/PositionBasedDynamics-ElasticRod
// korzenio[at] gmail.com
//
class PositionBasedElasticRods
{
public:
/** Determine the position corrections for a perpendicular bisector constraint:\n\n
* \f$C(\mathbf{p}_0, \mathbf{p}_1, \mathbf{p}_2) = ( \mathbf{p}_1 - 0.5 (\mathbf{p}_0 + \mathbf{p}_1))^T (\mathbf{p}_1 - \mathbf{p}_0) = 0\f$\n\n
*
* @param p0 position of first particle
* @param invMass0 inverse mass of first particle
* @param p1 position of second particle
* @param invMass1 inverse mass of second particle
* @param p2 position of third particle
* @param invMass2 inverse mass of third particle
* @param stiffness stiffness coefficient
* @param corr0 position correction of first particle
* @param corr1 position correction of second particle
* @param corr2 position correction of third particle
*/
static bool solve_PerpendiculaBisectorConstraint(
const Vector3r &p0, Real invMass0,
const Vector3r &p1, Real invMass1,
const Vector3r &p2, Real invMass2,
const Real stiffness,
Vector3r &corr0, Vector3r &corr1, Vector3r &corr2);
/** Determine the position corrections for a constraint that enforces a rest length between an edge and a ghost point:\n\n
* \f$C(\mathbf{p}_0, \mathbf{p}_1, \mathbf{p}_2) = \| ( 0.5 (\mathbf{p}_0 + \mathbf{p}_1) - \mathbf{p}_2 \| - L_0 = 0\f$\n\n
*
* @param p0 position of first particle
* @param invMass0 inverse mass of first particle
* @param p1 position of second particle
* @param invMass1 inverse mass of second particle
* @param p2 position of third particle
* @param invMass2 inverse mass of third particle
* @param stiffness stiffness coefficient
* @param ghostEdgeRestLength rest length
* @param corr0 position correction of first particle
* @param corr1 position correction of second particle
* @param corr2 position correction of third particle
*/
static bool solve_GhostPointEdgeDistanceConstraint(
const Vector3r& p0, Real invMass0,
const Vector3r& p1, Real invMass1,
const Vector3r& p2, Real invMass2,
const Real stiffness,
const Real ghostEdgeRestLength,
Vector3r& corr0, Vector3r& corr1, Vector3r& corr2);
/** Determine the position corrections for the Darboux vector constraint (eq. 21 in the paper). See the paper appendix for derivation details\n\n
*
* @param p0 position of first particle
* @param invMass0 inverse mass of first particle
* @param p1 position of second particle
* @param invMass1 inverse mass of second particle
* @param p2 position of third particle
* @param invMass2 inverse mass of third particle
* @param p3 position of fourth particle
* @param invMass3 inverse mass of fourth particle
* @param p4 position of fifth particle
* @param invMass4 inverse mass of fifth particle
* @param bendingAndTwistingKs stiffness coefficients for bending and twisting
* @param midEdgeLength average edge length
* @param restDarbouxVector Darboux vector in rest state
* @param corr0 position correction of first particle
* @param corr1 position correction of second particle
* @param corr2 position correction of third particle
* @param corr3 position correction of fourth particle
* @param corr4 position correction of fifth particle
*/
static bool solve_DarbouxVectorConstraint(
const Vector3r& p0, Real invMass0,
const Vector3r& p1, Real invMass1,
const Vector3r& p2, Real invMass2,
const Vector3r& p3, Real invMass3,
const Vector3r& p4, Real invMass4,
const Vector3r& bendingAndTwistingKs,
const Real midEdgeLength,
const Vector3r& restDarbouxVector,
Vector3r& oa, Vector3r& ob, Vector3r& oc, Vector3r& od, Vector3r& oe);
/** Computes the material frame (eq. 3 in the paper)
*/
static bool computeMaterialFrame(
const Vector3r& p0, //1st centreline point id
const Vector3r& p1, //2nd centreline point id
const Vector3r& p2, //corresponding ghost point
Matrix3r& frame); //resulting material frame
/** Computes the Darboux Vector (eq. 10 in the paper)
*/
static bool computeDarbouxVector(
const Matrix3r& dA, //1st material frame
const Matrix3r& dB, //2nd material frame
const Real mid_edge_length, //
Vector3r& darboux_vector); //resulting darboux vector
/** Computes the material frame derivatives (eq. 43, 44 and 45 in the appendix)
*/
static bool computeMaterialFrameDerivative(
const Vector3r& p0, const Vector3r& p1, const Vector3r& p2, // points
const Matrix3r& d, //corresponding material frame
Matrix3r& d1p0, Matrix3r& d1p1, Matrix3r& d1p2, //resulting matrices
Matrix3r& d2p0, Matrix3r& d2p1, Matrix3r& d2p2, //resulting matrices
Matrix3r& d3p0, Matrix3r& d3p1, Matrix3r& d3p2); //resulting matrices
/** Compute the Darboux gradient in respect to each point (eq. 49-53 in the appendix)
*/
static bool computeDarbouxGradient(
const Vector3r& darboux_vector, //Darboux vector
const Real length, //element length
const Matrix3r& dA, //1st material frame
const Matrix3r& dB, //2nd material frame
const Matrix3r[3][3], const Matrix3r[3][3], //material frames derivatives
//const Vector3r& bendAndTwistKs, //bending (x,y) and twisting (z) stiffness
Matrix3r& omega_pa, Matrix3r& omega_pb, Matrix3r& omega_pc, Matrix3r& omega_pd, Matrix3r& omega_pe); //resulting matrices
};
}
#endif
|
lst60916/Position_Based_Dynamics
|
Demos/Simulation/SimulationModel.h
|
<filename>Demos/Simulation/SimulationModel.h
#ifndef __SIMULATIONMODEL_H__
#define __SIMULATIONMODEL_H__
#include "Common/Common.h"
#include <vector>
#include "Demos/Simulation/RigidBody.h"
#include "Demos/Simulation/ParticleData.h"
#include "TriangleModel.h"
#include "TetModel.h"
#include "Demos/Utils/ObjectArray.h"
namespace PBD
{
class Constraint;
class SimulationModel
{
public:
SimulationModel();
virtual ~SimulationModel();
typedef std::vector<Constraint*> ConstraintVector;
typedef ObjectArray<RigidBodyContactConstraint> RigidBodyContactConstraintVector;
typedef ObjectArray<ParticleRigidBodyContactConstraint> ParticleRigidBodyContactConstraintVector;
typedef std::vector<RigidBody*> RigidBodyVector;
typedef std::vector<TriangleModel*> TriangleModelVector;
typedef std::vector<TetModel*> TetModelVector;
typedef std::vector<unsigned int> ConstraintGroup;
typedef std::vector<ConstraintGroup> ConstraintGroupVector;
protected:
RigidBodyVector m_rigidBodies;
TriangleModelVector m_triangleModels;
TetModelVector m_tetModels;
ParticleData m_particles;
ConstraintVector m_constraints;
RigidBodyContactConstraintVector m_rigidBodyContactConstraints;
ParticleRigidBodyContactConstraintVector m_particleRigidBodyContactConstraints;
ConstraintGroupVector m_constraintGroups;
Real m_cloth_stiffness;
Real m_cloth_bendingStiffness;
Real m_cloth_xxStiffness;
Real m_cloth_yyStiffness;
Real m_cloth_xyStiffness;
Real m_cloth_xyPoissonRatio;
Real m_cloth_yxPoissonRatio;
bool m_cloth_normalizeStretch;
bool m_cloth_normalizeShear;
Real m_solid_stiffness;
Real m_solid_poissonRatio;
bool m_solid_normalizeStretch;
bool m_solid_normalizeShear;
Real m_contactStiffnessRigidBody;
Real m_contactStiffnessParticleRigidBody;
public:
void reset();
void cleanup();
RigidBodyVector &getRigidBodies();
ParticleData &getParticles();
TriangleModelVector &getTriangleModels();
TetModelVector &getTetModels();
ConstraintVector &getConstraints();
RigidBodyContactConstraintVector &getRigidBodyContactConstraints();
ParticleRigidBodyContactConstraintVector &getParticleRigidBodyContactConstraints();
ConstraintGroupVector &getConstraintGroups();
bool m_groupsInitialized;
void resetContacts();
void addTriangleModel(
const unsigned int nPoints,
const unsigned int nFaces,
Vector3r *points,
unsigned int* indices,
const TriangleModel::ParticleMesh::UVIndices& uvIndices,
const TriangleModel::ParticleMesh::UVs& uvs);
void addTetModel(
const unsigned int nPoints,
const unsigned int nTets,
Vector3r *points,
unsigned int* indices);
void updateConstraints();
void initConstraintGroups();
bool addBallJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos);
bool addBallOnLineJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &dir);
bool addHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &axis);
bool addTargetAngleMotorHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &axis);
bool addTargetVelocityMotorHingeJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &axis);
bool addUniversalJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &axis1, const Vector3r &axis2);
bool addSliderJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &axis);
bool addTargetPositionMotorSliderJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &axis);
bool addTargetVelocityMotorSliderJoint(const unsigned int rbIndex1, const unsigned int rbIndex2, const Vector3r &pos, const Vector3r &axis);
bool addRigidBodyParticleBallJoint(const unsigned int rbIndex, const unsigned int particleIndex);
bool addRigidBodyContactConstraint(const unsigned int rbIndex1, const unsigned int rbIndex2,
const Vector3r &cp1, const Vector3r &cp2,
const Vector3r &normal, const Real dist,
const Real restitutionCoeff, const Real frictionCoeff);
bool addParticleRigidBodyContactConstraint(const unsigned int particleIndex, const unsigned int rbIndex,
const Vector3r &cp1, const Vector3r &cp2,
const Vector3r &normal, const Real dist,
const Real restitutionCoeff, const Real frictionCoeff);
bool addDistanceConstraint(const unsigned int particle1, const unsigned int particle2);
bool addDihedralConstraint( const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4);
bool addIsometricBendingConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4);
bool addFEMTriangleConstraint(const unsigned int particle1, const unsigned int particle2, const unsigned int particle3);
bool addStrainTriangleConstraint(const unsigned int particle1, const unsigned int particle2, const unsigned int particle3);
bool addVolumeConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4);
bool addFEMTetConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4);
bool addStrainTetConstraint(const unsigned int particle1, const unsigned int particle2,
const unsigned int particle3, const unsigned int particle4);
bool addShapeMatchingConstraint(const unsigned int numberOfParticles, const unsigned int particleIndices[], const unsigned int numClusters[]);
Real getClothStiffness() const { return m_cloth_stiffness; }
void setClothStiffness(Real val) { m_cloth_stiffness = val; }
Real getClothBendingStiffness() const { return m_cloth_bendingStiffness; }
void setClothBendingStiffness(Real val) { m_cloth_bendingStiffness = val; }
Real getClothXXStiffness() const { return m_cloth_xxStiffness; }
void setClothXXStiffness(Real val) { m_cloth_xxStiffness = val; }
Real getClothYYStiffness() const { return m_cloth_yyStiffness; }
void setClothYYStiffness(Real val) { m_cloth_yyStiffness = val; }
Real getClothXYStiffness() const { return m_cloth_xyStiffness; }
void setClothXYStiffness(Real val) { m_cloth_xyStiffness = val; }
bool getClothNormalizeStretch() const { return m_cloth_normalizeStretch; }
void setClothNormalizeStretch(bool val) { m_cloth_normalizeStretch = val; }
bool getClothNormalizeShear() const { return m_cloth_normalizeShear; }
void setClothNormalizeShear(bool val) { m_cloth_normalizeShear = val; }
Real getClothXYPoissonRatio() const { return m_cloth_xyPoissonRatio; }
void setClothXYPoissonRatio(Real val) { m_cloth_xyPoissonRatio = val; }
Real getClothYXPoissonRatio() const { return m_cloth_yxPoissonRatio; }
void setClothYXPoissonRatio(Real val) { m_cloth_yxPoissonRatio = val; }
Real getSolidStiffness() const { return m_solid_stiffness; }
void setSolidStiffness(Real val) { m_solid_stiffness = val; }
Real getSolidPoissonRatio() { return m_solid_poissonRatio; }
void setSolidPoissonRatio(const Real val) { m_solid_poissonRatio = val; }
bool getSolidNormalizeStretch() const { return m_solid_normalizeStretch; }
void setSolidNormalizeStretch(bool val) { m_solid_normalizeStretch = val; }
bool getSolidNormalizeShear() const { return m_solid_normalizeShear; }
void setSolidNormalizeShear(bool val) { m_solid_normalizeShear = val; }
Real getContactStiffnessRigidBody() const { return m_contactStiffnessRigidBody; }
void setContactStiffnessRigidBody(Real val) { m_contactStiffnessRigidBody = val; }
Real getContactStiffnessParticleRigidBody() const { return m_contactStiffnessParticleRigidBody; }
void setContactStiffnessParticleRigidBody(Real val) { m_contactStiffnessParticleRigidBody = val; }
};
}
#endif
|
HelpGiveThanks/BudgetPlanner
|
scripts/CloseWindowHaltScript.c
|
CloseWindowHaltScript
Close Window [ Current Window ]
Halt Script
February 6, 平成26 9:30:18 Budget Planner.fp7 - CloseWindowHaltScript -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/deleteIncome.c
|
deleteIncome
Set Variable [ $delete; Value:in::_Lin ]
Go to Field [ in::date ]
Scroll Window
[ To Selection ]
Go to Field [ ]
Refresh Window
Show Custom Dialog [ Message: "delete current record?"; Buttons: “cancel”, “delete” ]
If [ Get (LastMessageChoice) = 1 ]
Set Variable [ $delete ]
Refresh Window
Exit Script [ ]
End If
Delete Record/Request
[ No dialog ]
Perform Script [ “updateIncomeHeaderCalc” ]
January 8, 平成26 19:05:04 Budget Research.fp7 - deleteIncome -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/updateIncomeHeaderCalc.c
|
updateIncomeHeaderCalc
If [ Get (FoundCount) = 0 ]
New Record/Request
Set Variable [ $delete; Value:1 ]
End If
If [ out::UpdateCalcField = "" ]
Set Field [ in::UpdateCalcField; "t" ]
Else
Set Field [ in::UpdateCalcField; "" ]
End If
Commit Records/Requests
Refresh Window
If [ $delete = 1 ]
Delete Record/Request
[ No dialog ]
End If
January 8, 平成26 19:12:26 Budget Research.fp7 - updateIncomeHeaderCalc -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/returnToMoneyFromSource.c
|
<reponame>HelpGiveThanks/BudgetPlanner<gh_stars>0
returnToMoneyFromSource
Go to Layout [ “income2” (in) ]
January 8, 平成26 19:00:15 Budget Research.fp7 - returnToMoneyFromSource -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/duplicateIncome.c
|
<filename>scripts/duplicateIncome.c
duplicateIncome
Allow User Abort [ Off ]
Set Error Capture [ On ]
Set Variable [ $record; Value:in::_Lin ]
Set Variable [ $date; Value:in::date ]
New Window [ ]
New Record/Request
Set Variable [ $recordDuplicate; Value:in::_Lin ]
Delete Record/Request
[ No dialog ]
Enter Find Mode [ ]
Set Field [ in::_Lin; $record ]
Perform Find [ ]
Duplicate Record/Request
Set Field [ in::_Lin; $recordDuplicate ]
Set Field [ in::date; Case ( Month ( $date ) + 1 = 13 ;
1 & "/" & 1 & "/" & Year ( $date ) + 1 ;
( Month ( $date ) + 1 ) & "/" & 1 & "/" & Year ( $date ) ) ]
Close Window [ Current Window ]
Show All Records
Sort Records [ ]
[ No dialog ]
Loop
Go to Record/Request/Page
[ Next; Exit after last ]
Exit Loop If [ out::_Lout = $recordDuplicate ]
End Loop
Perform Script [ “updateIncomeHeaderCalc” ]
Go to Field [ ]
January 8, 平成26 18:54:56 Budget Research.fp7 - duplicateIncome -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/moreInfo.c
|
<gh_stars>0
moreInfo
New Window [ Name: "More Info"; Left: Get ( WindowDesktopWidth ) - (Get ( WindowDesktopWidth ) / 2 ) ]
Go to Layout [ “moreInfo” (budget) ]
Adjust Window
[ Resize to Fit ]
Pause/Resume Script [ Indefinitely ]
February 6, 平成26 9:28:43 Budget Planner.fp7 - moreInfo -1-
|
HelpGiveThanks/BudgetPlanner
|
scripts/gotoSource.c
|
gotoSource
Set Error Capture [ On ]
Allow User Abort [ Off ]
Set Field [ budget::inLayoutGlobal; Get (LayoutName) ]
Go to Layout [ “source” (source) ]
Enter Find Mode [ ]
Set Field [ source::kbudget; budget::budgetGlobal ]
Perform Find [ ]
Sort Records [ Specified Sort Order: source::source; ascending ]
[ Restore; No dialog ]
Go to Record/Request/Page
[ First ]
January 8, 平成26 18:50:03 Budget Research.fp7 - gotoSource -1-
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.