Skip to content

Implement edge activated hats #630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/scratchcpp/compiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class LIBSCRATCHCPP_EXPORT Compiler
Target *target() const;
std::shared_ptr<Block> block() const;

std::shared_ptr<ExecutableCode> compile(std::shared_ptr<Block> startBlock);
std::shared_ptr<ExecutableCode> compile(std::shared_ptr<Block> startBlock, bool isHatPredicate = false);
void preoptimize();

CompilerValue *addFunctionCall(const std::string &functionName, StaticType returnType = StaticType::Void, const ArgTypes &argTypes = {}, const Args &args = {});
Expand Down
3 changes: 3 additions & 0 deletions include/scratchcpp/executablecode.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ class LIBSCRATCHCPP_EXPORT ExecutableCode
/*! Runs the script until it finishes or yields. */
virtual void run(ExecutionContext *context) = 0;

/*! Runs the hat predicate and returns its return value. */
virtual bool runPredicate(ExecutionContext *context) = 0;

/*! Stops the code. isFinished() will return true. */
virtual void kill(ExecutionContext *context) = 0;

Expand Down
3 changes: 3 additions & 0 deletions include/scratchcpp/script.h
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ class LIBSCRATCHCPP_EXPORT Script
ExecutableCode *code() const;
void setCode(std::shared_ptr<ExecutableCode> code);

ExecutableCode *hatPredicateCode() const;
void setHatPredicateCode(std::shared_ptr<ExecutableCode> code);

bool runHatPredicate(Target *target);

std::shared_ptr<Thread> start();
Expand Down
1 change: 1 addition & 0 deletions include/scratchcpp/thread.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class LIBSCRATCHCPP_EXPORT Thread
Script *script() const;

void run();
bool runPredicate();
void kill();
void reset();

Expand Down
83 changes: 83 additions & 0 deletions src/blocks/eventblocks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,21 @@
#include <scratchcpp/iengine.h>
#include <scratchcpp/compiler.h>
#include <scratchcpp/block.h>
#include <scratchcpp/input.h>
#include <scratchcpp/field.h>
#include <scratchcpp/broadcast.h>
#include <scratchcpp/executioncontext.h>
#include <scratchcpp/thread.h>
#include <scratchcpp/compilerconstant.h>
#include <scratchcpp/promise.h>
#include <scratchcpp/stringptr.h>
#include <scratchcpp/sprite.h>
#include <scratchcpp/itimer.h>
#include <utf8.h>

#include "eventblocks.h"
#include "audio/audioinput.h"
#include "audio/iaudioloudness.h"

using namespace libscratchcpp;

Expand All @@ -33,6 +38,7 @@ Rgb EventBlocks::color() const

void EventBlocks::registerBlocks(IEngine *engine)
{
// Blocks
engine->addCompileFunction(this, "event_whentouchingobject", &compileWhenTouchingObject);
engine->addCompileFunction(this, "event_whenflagclicked", &compileWhenFlagClicked);
engine->addCompileFunction(this, "event_whenthisspriteclicked", &compileWhenThisSpriteClicked);
Expand All @@ -43,6 +49,10 @@ void EventBlocks::registerBlocks(IEngine *engine)
engine->addCompileFunction(this, "event_broadcast", &compileBroadcast);
engine->addCompileFunction(this, "event_broadcastandwait", &compileBroadcastAndWait);
engine->addCompileFunction(this, "event_whenkeypressed", &compileWhenKeyPressed);

// Hat predicates
engine->addHatPredicateCompileFunction(this, "event_whentouchingobject", &compileWhenTouchingObjectPredicate);
engine->addHatPredicateCompileFunction(this, "event_whengreaterthan", &compileWhenGreaterThanPredicate);
}

CompilerValue *EventBlocks::compileWhenTouchingObject(Compiler *compiler)
Expand All @@ -51,6 +61,21 @@ CompilerValue *EventBlocks::compileWhenTouchingObject(Compiler *compiler)
return nullptr;
}

CompilerValue *EventBlocks::compileWhenTouchingObjectPredicate(Compiler *compiler)
{
Input *input = compiler->input("TOUCHINGOBJECTMENU");
CompilerValue *name = nullptr;

if (input->pointsToDropdownMenu()) {
std::string value = input->selectedMenuItem();

name = compiler->addConstValue(value);
} else
name = compiler->addInput(input);

return compiler->addTargetFunctionCall("event_whentouchingobject_predicate", Compiler::StaticType::Bool, { Compiler::StaticType::String }, { name });
}

CompilerValue *EventBlocks::compileWhenFlagClicked(Compiler *compiler)
{
compiler->engine()->addGreenFlagScript(compiler->block());
Expand Down Expand Up @@ -99,6 +124,27 @@ CompilerValue *EventBlocks::compileWhenGreaterThan(Compiler *compiler)
return nullptr;
}

CompilerValue *EventBlocks::compileWhenGreaterThanPredicate(Compiler *compiler)
{
Field *field = compiler->field("WHENGREATERTHANMENU");
std::string predicate;

if (field) {
const std::string option = field->value().toString();

if (option == "LOUDNESS")
predicate = "event_whengreaterthan_loudness_predicate";
else if (option == "TIMER")
predicate = "event_whengreaterthan_timer_predicate";
else
return compiler->addConstValue(false);
} else
return compiler->addConstValue(false);

CompilerValue *value = compiler->addInput("VALUE");
return compiler->addFunctionCallWithCtx(predicate, Compiler::StaticType::Bool, { Compiler::StaticType::Number }, { value });
}

CompilerValue *EventBlocks::compileBroadcast(Compiler *compiler)
{
auto input = compiler->addInput("BROADCAST_INPUT");
Expand Down Expand Up @@ -127,6 +173,43 @@ CompilerValue *EventBlocks::compileWhenKeyPressed(Compiler *compiler)
return nullptr;
}

extern "C" bool event_whentouchingobject_predicate(Target *target, const StringPtr *name)
{
static const StringPtr MOUSE_STR = StringPtr("_mouse_");
static const StringPtr EDGE_STR = StringPtr("_edge_");

IEngine *engine = target->engine();

if (string_compare_case_sensitive(name, &MOUSE_STR) == 0)
return target->touchingPoint(engine->mouseX(), engine->mouseY());
else if (string_compare_case_sensitive(name, &EDGE_STR) == 0)
return target->touchingEdge();
else {
// TODO: Use UTF-16 in engine
const std::string u8name = utf8::utf16to8(std::u16string(name->data));
Target *anotherTarget = engine->targetAt(engine->findTarget(u8name));

if (anotherTarget && !anotherTarget->isStage())
return target->touchingSprite(static_cast<Sprite *>(anotherTarget));
else
return false;
}
}

extern "C" bool event_whengreaterthan_loudness_predicate(ExecutionContext *ctx, double value)
{
if (!EventBlocks::audioInput)
EventBlocks::audioInput = AudioInput::instance().get();

auto audioLoudness = EventBlocks::audioInput->audioLoudness();
return (audioLoudness->getLoudness() > value);
}

extern "C" bool event_whengreaterthan_timer_predicate(ExecutionContext *ctx, double value)
{
return ctx->engine()->timer()->value() > value;
}

extern "C" void event_broadcast(ExecutionContext *ctx, const StringPtr *name, bool wait)
{
Thread *thread = ctx->thread();
Expand Down
6 changes: 6 additions & 0 deletions src/blocks/eventblocks.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
namespace libscratchcpp
{

class IAudioInput;

class EventBlocks : public IExtension
{
public:
Expand All @@ -16,14 +18,18 @@ class EventBlocks : public IExtension

void registerBlocks(IEngine *engine) override;

static inline IAudioInput *audioInput = nullptr;

private:
static CompilerValue *compileWhenTouchingObject(Compiler *compiler);
static CompilerValue *compileWhenTouchingObjectPredicate(Compiler *compiler);
static CompilerValue *compileWhenFlagClicked(Compiler *compiler);
static CompilerValue *compileWhenThisSpriteClicked(Compiler *compiler);
static CompilerValue *compileWhenStageClicked(Compiler *compiler);
static CompilerValue *compileWhenBroadcastReceived(Compiler *compiler);
static CompilerValue *compileWhenBackdropSwitchesTo(Compiler *compiler);
static CompilerValue *compileWhenGreaterThan(Compiler *compiler);
static CompilerValue *compileWhenGreaterThanPredicate(Compiler *compiler);
static CompilerValue *compileBroadcast(Compiler *compiler);
static CompilerValue *compileBroadcastAndWait(Compiler *compiler);
static CompilerValue *compileWhenKeyPressed(Compiler *compiler);
Expand Down
23 changes: 21 additions & 2 deletions src/engine/compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ std::shared_ptr<libscratchcpp::Block> Compiler::block() const
}

/*! Compiles the script starting with the given block. */
std::shared_ptr<ExecutableCode> Compiler::compile(std::shared_ptr<Block> startBlock)
std::shared_ptr<ExecutableCode> Compiler::compile(std::shared_ptr<Block> startBlock, bool isHatPredicate)
{
BlockPrototype *procedurePrototype = nullptr;

Expand All @@ -60,13 +60,32 @@ std::shared_ptr<ExecutableCode> Compiler::compile(std::shared_ptr<Block> startBl
}
}

impl->builder = impl->builderFactory->create(impl->ctx, procedurePrototype);
impl->builder = impl->builderFactory->create(impl->ctx, procedurePrototype, isHatPredicate);
impl->substackTree.clear();
impl->substackHit = false;
impl->emptySubstack = false;
impl->warp = false;
impl->block = startBlock;

if (impl->block && isHatPredicate) {
auto f = impl->block->hatPredicateCompileFunction();

if (f) {
CompilerValue *ret = f(this);
assert(ret);

if (!ret)
std::cout << "warning: '" << impl->block->opcode() << "' hat predicate compile function doesn't return a valid value" << std::endl;
} else {
std::cout << "warning: unsupported hat predicate: " << impl->block->opcode() << std::endl;
impl->unsupportedBlocks.insert(impl->block->opcode());
addConstValue(false); // return false if unsupported
}

impl->block = nullptr;
return impl->builder->finalize();
}

while (impl->block) {
if (impl->block->compileFunction()) {
assert(impl->customIfStatementCount == 0);
Expand Down
4 changes: 2 additions & 2 deletions src/engine/internal/codebuilderfactory.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ std::shared_ptr<CodeBuilderFactory> CodeBuilderFactory::instance()
return m_instance;
}

std::shared_ptr<ICodeBuilder> CodeBuilderFactory::create(CompilerContext *ctx, BlockPrototype *procedurePrototype) const
std::shared_ptr<ICodeBuilder> CodeBuilderFactory::create(CompilerContext *ctx, BlockPrototype *procedurePrototype, bool isPredicate) const
{
assert(dynamic_cast<LLVMCompilerContext *>(ctx));
return std::make_shared<LLVMCodeBuilder>(static_cast<LLVMCompilerContext *>(ctx), procedurePrototype);
return std::make_shared<LLVMCodeBuilder>(static_cast<LLVMCompilerContext *>(ctx), procedurePrototype, isPredicate);
}

std::shared_ptr<CompilerContext> CodeBuilderFactory::createCtx(IEngine *engine, Target *target) const
Expand Down
2 changes: 1 addition & 1 deletion src/engine/internal/codebuilderfactory.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class CodeBuilderFactory : public ICodeBuilderFactory
{
public:
static std::shared_ptr<CodeBuilderFactory> instance();
std::shared_ptr<ICodeBuilder> create(CompilerContext *ctx, BlockPrototype *procedurePrototype) const override;
std::shared_ptr<ICodeBuilder> create(CompilerContext *ctx, BlockPrototype *procedurePrototype, bool isPredicate) const override;
std::shared_ptr<CompilerContext> createCtx(IEngine *engine, Target *target) const override;

private:
Expand Down
3 changes: 3 additions & 0 deletions src/engine/internal/engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,9 @@ void Engine::compile()
auto script = std::make_shared<Script>(target.get(), block, this);
m_scripts[block] = script;
script->setCode(compiler.compile(block));

if (block->hatPredicateCompileFunction())
script->setHatPredicateCode(compiler.compile(block, true));
} else {
std::cout << "warning: unsupported top level block: " << block->opcode() << std::endl;
m_unsupportedBlocks.insert(block->opcode());
Expand Down
2 changes: 1 addition & 1 deletion src/engine/internal/icodebuilderfactory.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class ICodeBuilderFactory
public:
virtual ~ICodeBuilderFactory() { }

virtual std::shared_ptr<ICodeBuilder> create(CompilerContext *ctx, BlockPrototype *procedurePrototype = nullptr) const = 0;
virtual std::shared_ptr<ICodeBuilder> create(CompilerContext *ctx, BlockPrototype *procedurePrototype = nullptr, bool isPredicate = false) const = 0;
virtual std::shared_ptr<CompilerContext> createCtx(IEngine *engine, Target *target) const = 0;
};

Expand Down
32 changes: 22 additions & 10 deletions src/engine/internal/llvm/llvmcodebuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,16 @@ static std::unordered_map<ValueType, Compiler::StaticType>
static const std::unordered_set<LLVMInstruction::Type>
VAR_LIST_READ_INSTRUCTIONS = { LLVMInstruction::Type::ReadVariable, LLVMInstruction::Type::GetListItem, LLVMInstruction::Type::GetListItemIndex, LLVMInstruction::Type::ListContainsItem };

LLVMCodeBuilder::LLVMCodeBuilder(LLVMCompilerContext *ctx, BlockPrototype *procedurePrototype) :
LLVMCodeBuilder::LLVMCodeBuilder(LLVMCompilerContext *ctx, BlockPrototype *procedurePrototype, bool isPredicate) :
m_ctx(ctx),
m_target(ctx->target()),
m_llvmCtx(*ctx->llvmCtx()),
m_module(ctx->module()),
m_builder(m_llvmCtx),
m_procedurePrototype(procedurePrototype),
m_defaultWarp(procedurePrototype ? procedurePrototype->warp() : false),
m_warp(m_defaultWarp)
m_warp(m_defaultWarp),
m_isPredicate(isPredicate)
{
initTypes();
createVariableMap();
Expand All @@ -54,6 +55,10 @@ std::shared_ptr<ExecutableCode> LLVMCodeBuilder::finalize()

if (it == m_instructions.end())
m_warp = true;

// Do not create coroutine in hat predicates
if (m_isPredicate)
m_warp = true;
}

// Set fast math flags
Expand Down Expand Up @@ -1314,10 +1319,16 @@ std::shared_ptr<ExecutableCode> LLVMCodeBuilder::finalize()
// End and verify the function
llvm::PointerType *pointerType = llvm::PointerType::get(llvm::Type::getInt8Ty(m_llvmCtx), 0);

if (m_warp)
m_builder.CreateRet(llvm::ConstantPointerNull::get(pointerType));
else
coro->end();
if (m_isPredicate) {
// Use last instruction return value
assert(!m_instructions.empty());
m_builder.CreateRet(m_instructions.back()->functionReturnReg->value);
} else {
if (m_warp)
m_builder.CreateRet(llvm::ConstantPointerNull::get(pointerType));
else
coro->end();
}

verifyFunction(m_function);

Expand All @@ -1338,7 +1349,7 @@ std::shared_ptr<ExecutableCode> LLVMCodeBuilder::finalize()

verifyFunction(resumeFunc);

return std::make_shared<LLVMExecutableCode>(m_ctx, m_function->getName().str(), resumeFunc->getName().str());
return std::make_shared<LLVMExecutableCode>(m_ctx, m_function->getName().str(), resumeFunc->getName().str(), m_isPredicate);
}

CompilerValue *LLVMCodeBuilder::addFunctionCall(const std::string &functionName, Compiler::StaticType returnType, const Compiler::ArgTypes &argTypes, const Compiler::Args &args)
Expand Down Expand Up @@ -2008,7 +2019,7 @@ void LLVMCodeBuilder::popLoopScope()

std::string LLVMCodeBuilder::getMainFunctionName(BlockPrototype *procedurePrototype)
{
return procedurePrototype ? "proc." + procedurePrototype->procCode() : "script";
return procedurePrototype ? "proc." + procedurePrototype->procCode() : (m_isPredicate ? "predicate" : "script");
}

std::string LLVMCodeBuilder::getResumeFunctionName(BlockPrototype *procedurePrototype)
Expand All @@ -2019,7 +2030,8 @@ std::string LLVMCodeBuilder::getResumeFunctionName(BlockPrototype *procedureProt
llvm::FunctionType *LLVMCodeBuilder::getMainFunctionType(BlockPrototype *procedurePrototype)
{
// void *f(ExecutionContext *, Target *, ValueData **, List **, (warp arg), (procedure args...))
llvm::PointerType *pointerType = llvm::PointerType::get(llvm::Type::getInt8Ty(m_llvmCtx), 0);
// bool f(...) (hat predicates)
llvm::Type *pointerType = llvm::PointerType::get(llvm::Type::getInt8Ty(m_llvmCtx), 0);
std::vector<llvm::Type *> argTypes = { pointerType, pointerType, pointerType, pointerType };

if (procedurePrototype) {
Expand All @@ -2034,7 +2046,7 @@ llvm::FunctionType *LLVMCodeBuilder::getMainFunctionType(BlockPrototype *procedu
}
}

return llvm::FunctionType::get(pointerType, argTypes, false);
return llvm::FunctionType::get(m_isPredicate ? m_builder.getInt1Ty() : pointerType, argTypes, false);
}

llvm::Function *LLVMCodeBuilder::getOrCreateFunction(const std::string &name, llvm::FunctionType *type)
Expand Down
3 changes: 2 additions & 1 deletion src/engine/internal/llvm/llvmcodebuilder.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class LLVMLoopScope;
class LLVMCodeBuilder : public ICodeBuilder
{
public:
LLVMCodeBuilder(LLVMCompilerContext *ctx, BlockPrototype *procedurePrototype = nullptr);
LLVMCodeBuilder(LLVMCompilerContext *ctx, BlockPrototype *procedurePrototype = nullptr, bool isPredicate = false);

std::shared_ptr<ExecutableCode> finalize() override;

Expand Down Expand Up @@ -239,6 +239,7 @@ class LLVMCodeBuilder : public ICodeBuilder
bool m_defaultWarp = false;
bool m_warp = false;
int m_defaultArgCount = 0;
bool m_isPredicate = false; // for hat predicates

long m_loopScope = -1; // index
std::vector<std::shared_ptr<LLVMLoopScope>> m_loopScopes;
Expand Down
Loading